Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

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 

Comments on this snippet

gravatar icon
#1 Shaun Dubin on 2007-07-17 at 11:07

I was trying to implement what you have but not sure if I have the files in the correct place. Does

<?php

class myCallbackValidator extends sfCallbackValidator {

public function execute(&$value, &$error) {

$callback = $this-&gt;getParameterHolder()-&gt;get(&#039;callback&#039;);
if (!call_user_func($callback, $value, $this-&gt;getParameterHolder()-&gt;get(&#039;parameters&#039;))) {
  $error = $this-&gt;getParameterHolder()-&gt;get(&#039;invalid_error&#039;);
  return false;
}
return true;

}

}

go into a file called myCallbackValidator.class.php located in the /apps/[app name]/lib folder?

And does public static function birthDate($string, $params = null) { if (isset($params['min_age'])) { ... etc...

go into the actions.class.php?

gravatar icon
#2 Martín Palacio Pentucci on 2007-07-18 at 02:07

The definition of class 'myCallbackValidator' goes in a new file 'myCallbackValidator.class.php', can be in /apps/[app_name]/lib or in /lib.

The callback function can be into another class file, like 'myValidators.class.php', in the same location. That will help to reuse the code later, in other apps or symfony projects.

You need to create an account or log in to post a comment or rate this snippet.