Welcome Guest, Not a member yet? Register   Sign In
Very useful caveat in form validation callbacks
#1

[eluser]kaluzhanin[/eluser]
Greetings, and thank you for providing this great framework with great community.

I'd like to share a great feature of form validation callbacks (which I actually regarded as a bug at first): the ability to change values returned by $this->input->post().

I'm working at a project powered by CI and Doctrine. At some place I needed to validate the form against following conditions:
1. The login user provides must exist in 'user' table of my database.
2. The 'confirmed' field of user with that login should be 'false'.

The validation rule for this was as follows:

Code:
$this->form_validation->set_rules('username', 'login', 'callback__userExists|callback__needConfirmation');

The original code for callbacks was:

Code:
public function _userExists($username) {
    return Doctrine::getTable('user')->findOneByUsername($username);
}

public function _needConfirmation($username) {
    return Doctrine::getTable('user')->findOneByUsername($username)->confirmed;
}

Checking if user exists worked flawlessly, but I got mad with the second condition. I was getting "HQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens" errors. And then I found this innocent note in CI documentation: "If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.".

It's a really great feature. Now after calling _userExists, $this->input->post('username') contains an object fetched from the database, not a boring string. Second callback was rewriten to a simple:

Code:
public function _needConfirmation($username) {            
    return !$username->confirmed;
}

And as the object is now stored at $this->input->post('username'), I was able to use it in form processing logic after validating the input.

So if you need to load an object from the database, you may do it very conviently in form validation callbacks.

Drawback: you can't repopulate your form with set_value after this. Your thoughts on implementing it are welcomed.




Theme © iAndrew 2016 - Forum software by © MyBB