Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "validator callback"

Pass multiple parameters to sfCallbackValidator

I love sfCallbackValidator and use it all the time, but found it was somewhat limiting in that only the value being validated could be passed to the function or method that is doing the validating. So, I've extended it, overriding the execute method:

myCallbackValidator.class.php:

<?php
 
class myCallbackValidator extends sfCallbackValidator {
 
  public function execute(&$value, &$error) {
 
    $callback = $this->getParameterHolder()->get('callback');
    if (!call_user_func($callback, $value, $this->getParameterHolder()->get('parameters'))) {
      $error = $this->getParameterHolder()->get('invalid_error');
      return false;
    }
    return true;
 
  }
 
}

You can specify the parameters in your validation yaml file like so...

  birthdate:
    myCallbackValidator:
      callback:       [myValidationTools, birthDate]
      invalid_error:  Birthdate is invalid. You must be at least 18 years old to apply.
      parameters:
        min_age:      18

And then the parameters can be accessed in the callback function like so:

  public static function birthDate($string, $params = null) {
    if (isset($params['min_age'])) {
      ... etc...
by east3rd on 2007-06-27, tagged callback  validation  validator 
(2 comments)