A simple example on how to use post validators in symfony

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!

2 Comments

  1. pfwd

    This is great example of how to use callbacks. Thanks for posting

    Reply

    • Jacob Mather

      You’re welcome! Thanks for reading! 🙂

      Reply

Leave a Reply to Jacob Mather Cancel

*

twitter