![]() |
|
Snippets |
|
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...
Comments on this snippet
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) {
}
}
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?
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.