views:

36

answers:

1

Hi,

Apologies if this is an oversight or sheer stupidity on my part but I can't quite figure out how to access the validation array from a callback in a model (using ORM and KO 2.3.4). I want to be able to add specific error messages to the validation array if a callback returns false.

e.g This register method:

public function register(array & $array, $save = FALSE)
{
    // Initialise the validation library and setup some rules
    $array = Validation::factory($array)
            ->pre_filter('trim')
            ->add_rules('email', 'required', 'valid::email', array($this, 'email_available'))
            ->add_rules('confirm_email', 'matches[email]')
            ->add_rules('password', 'required', 'length[5,42]')
            ->add_rules('confirm_password', 'matches[password]');

    return ORM::validate($array, $save);
}

Callback:

public function email_available($value)
{
    return ! (bool) $this->db
        ->where('email', $value)
        ->count_records($this->table_name);
}

I can obviously access the current model from the callback, but I was wondering what the best way to add custom error from the callback would be?

+1  A: 

Your "callback" is not a callback, but a rule. What you want is:

$array->add_callback('email', array($this, 'email_available'));

Then your callback will look like this:

public function email_available(Validation $array, $input)
{
    if ($value = $array[$input])
    {
        $result = (bool) $this->db
            ->where('email', $value)
            ->count_records($this->table_name);

        if ( ! $result)
        {
            $array->add_error($input, 'Email address is not available');
        }
    }
}
shadowhand
Thanks SH - got mixed up between rules and callbacks
kenny99