It's possible, when validating a form, to check if a field is correct dependently of an other field's value.
First, in your configure method, after the declaration of your validators, add :
$this->validatorSchema->setPostValidator( new sfValidatorCallback( array('callback' => array($this, 'checkRequiredFields')) ) );
And create a new method in your form class !
public function checkRequiredFields($validator, $values) { $errors = array(); /** * checking if mandatory_field == 3, then other_field must be filled */ if(3 == $values['mandatory_field'] && null == $values['other_field']) { $error = new sfValidatorError($validator, 'if you choose the option 3 for mandatory_field, you need to fill the other_field'); $errors['other_field'] = $error; //throw new sfValidatorErrorSchema($validator, array('other_field' => $error)); } else { // nothing to check } /** * checking if foo is selected, then bar must be filled */ if(1 == $values['foo'] && null == $values['bar']) { $error = new sfValidatorError($validator, 'if you check foo, you need to fill bar'); $errors['bar'] = $error; } else { // nothing to check } /** * more depency checking here */ /** * if there is errors */ if(count($errors)) { throw new sfValidatorErrorSchema($validator, $errors); } /** * dont forget to return values ! */ return $values; }
2010-02-23 Updated: All errors are now returned once. 2010-02-23 Updated: Deleted the commented throw, added another check.