Below are the snippets on how to implement a conditional validation in the form. i.e. validate field A if field B is true
As discussed in this tutorial (though it is for symfony 1.2, it will works in 1.4), the key thing is to set a post validator to validate values after the initial validation.
Assuming you have two fields – one checkbox and one textfield.
And you want the textfield to be filled in if the checkbox is ticked.
Here’s how you do it.
// lib\form\doctrine\MyForm.class.php
class MyForm extends BaseContestForm
{
public function configure()
{
// add a post validator
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'validateTextField')))
);
}
public function validateTextField($validator, $values)
{
if ($values['myCheckbox'])
{
$this->validatorSchema['myTextField'] = new sfValidatorString(array(
'required' => true,
'max_length' => 50,
'min_length' => 1
));
}
return $values;
}
}