symfony 1.4有条件验证送货地址

时间:2012-11-20 14:33:19

标签: symfony-1.4 symfony-forms

如何根据bill_ceck post参数验证帐单邮寄地址?

我查看了帖子验证(http://symfony.com/legacy/doc/cookbook/1_2/en/conditional-validator),但在我看来,它似乎是AND验证而不是OR。

class OrderAddForm extends BaseOprOrderHeaderForm {
  public function configure() {
    $this->setWidgets(array(
        'email' => new sfWidgetFormInputText(),
        'name' => new sfWidgetFormInputText(),
        //....
        'city' => new sfWidgetFormInputText(),
        'street' => new sfWidgetFormInputText(),
        //....
        'bill_check' => new sfWidgetFormInputCheckbox(),
        'bill_name' => new sfWidgetFormInputText(),
        'bill_city' => new sfWidgetFormInputText(),
        'bill_street' => new sfWidgetFormInputText(),
        //....
    ));
    $this->widgetSchema['bill_check']->setOption('value_attribute_value', 1);
    $this->setValidators(array(
        'email' => new sfValidatorEmail(),
        'name' => new sfValidatorString(),
        //...
        'city' => new sfValidatorString(),
        'street' => new sfValidatorString(),
        //...
        'bill_check' => new sfValidatorBoolean(),
    ));
    if (/** the most convetional solution to check 'bill_check' state */) {
      $this->validatorSchema['bill_name'] = new sfValidatorString();
      $this->validatorSchema['bill_city'] = new sfValidatorString();
      $this->validatorSchema['bill_street'] = new sfValidatorString();
      //....
    }
    $this->widgetSchema->setNameFormat('orderAddForm[%s]');
  }
}

感谢, 奥利弗

1 个答案:

答案 0 :(得分:2)

您可以使用postValidator

public function configure() {
  // your current code
  $this->validatorSchema->setPostValidator(
    new sfValidatorCallback(array('callback' => array($this, 'checkOtherStuff')))
  );
}

public function checkOtherStuff($validator, $values)
{
  // $values is an array of POSTed values
  if ($values['bill_check'] == 'something in here')
  {
    if ($values['bill_city'] == '' || $values['bill_street'] == '') {
        throw new sfValidatorError($validator, 'You must complete all fields');
    }
  }
  // bill_check is correct, return the clean values
  return $values;
}

Blog article on the subject here