Using sfValidatorCallback

by rp

Writing this post down as a note to self about using sfValidatorCallback.
Step 1: add the sfValidatorCallback to the widget

public function configure()
{
  $this->widgetSchema['my_field'] =
    new sfWidgetFormTextArea(array('required' => false));
  // add the validator
  $this->validatorSchema['my_field']   = new sfValidatorCallback(
      array('callback' => array(
          array($this, 'my_valdiation_function')   // if you write the function in the validator itself
          // array($this->getObject(), 'my_valdiation_function')   // or if you move it to your model object
        ))
    );
}

As you can see form the code, I have commented out a line, that’s if you think its a good idea to move the validator to the model. I am not sure if I buy that idea but this what I have seen some developers do. I guess it kinda depends on what they are after, I would rather keep it all together unless it has its value in being shared across other classes.

And finally the signature for actual callback function:

public function my_valdiation_function($validator, $value) {
  if ($condition_is_satisfied) {
    return $value;
  } else {
    $message = 'message detailing reason for EPIC FAIL!';
    throw new sfValidatorError($validator, $message);
  }
}