[eluser]Unknown[/eluser]
Hi to all
I want to share with all my own version of this library with better support for callbacks
Example usage:
Code:
// Register the callback 'foo_bar' which is a method inside the current object, i.e. a model object
$this->form_validation->set_callback('foo_bar', array($this, 'foo_bar'));
// The example rule
$this->form_validation->set_rules('my_field', 'My field', 'trim|required|max_lenght[45]|callback[foo_bar,1,2,3]');
// The callback method
public function foo_bar($str, $arg1, $arg2, $arg3)
{
return $arg1 + $arg2 + $arg3;
}
// Inside a language file...
$lang['callback_foo_bar'] = "blah blah blah blah...';
And here's the code
Code:
/**
* Enhanced callback functionality
*
* @author Miguel Ayllón
*/
class MY_Form_validation extends CI_Form_validation
{
var $_callbacks = array();
public function __construct($rules = array())
{
parent::__construct($rules);
}
/**
* Register a callback
*
* @param string $name
* @param callback $func
*/
public function set_callback($name, $func)
{
$this->_callbacks[$name] = $func;
}
/**
* Runs a registered callback
*
* @param string $str
* @param mixed $args
* @return mixed
*/
public function callback($str, $args = '')
{
// Parse comma separated arguments
if ( ! is_array($args))
{
$args = explode(',', $args);
}
// Find the callback
if (count($args))
{
$name = array_shift($args);
if (isset($this->_callbacks[$name]) && is_callable($this->_callbacks[$name]))
{
array_unshift($args, $str);
$result = call_user_func_array($this->_callbacks[$name], $args);
// Set an error message if required
if ($result === FALSE)
{
if (FALSE === ($line = $this->CI->lang->line('callback_' . $name)))
{
$line = 'Callback: Unable to access an error message corresponding to your field name.';
}
$this->set_message('callback', $line);
}
return $result;
}
}
return FALSE;
}
}
Hope you find useful