Someone came into the #symfony channel on freenode asking how to add conditional validators that would require a text box to be filled out when a checkbox was ticked. As I realize this is a common question (though the circumstances may change), I wanted to put this example up here as well, for others.
Here's the example:
class TestForm { public function configure() { // ... snip ... $this->validatorSchema->setPostValidator( new sfValidatorCallback(array('callback' => array($this, 'contextualChecks'))) ); } public function contextualChecks($validator, $values) { if ($values['checkbox_1'] == 1) { if ($values['textbox_for_checkbox_1'] == '') { $error = new sfValidatorError($validator, 'Field is required when Checkbox 1 is checked.'); $ves = new sfValidatorErrorSchema($validator, array('textbox_for_checkbox_1' => $error)); throw $ves; } } return $values; } } |
Note: I completely left out returning $values in the initial draft. I apologize!
pfwd
November 17, 2010 @ 3:03 pm
This is great example of how to use callbacks. Thanks for posting
Jacob Mather
November 17, 2010 @ 6:19 pm
You’re welcome! Thanks for reading! đŸ™‚