Welcome Guest, Not a member yet? Register   Sign In
[SOLVED] Setting form validation error messages after a "successful" validation
#1

[eluser]bluematt[/eluser]
I have this bit of controller code:

Code:
function create() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('type[name]', 'type name', 'trim|required|max_length[40]');
        $this->form_validation->set_rules('type[description]', 'type name', 'trim|max_length[200]');
        if (
            $this->form_validation->run()
                &&
            $this->types->create($this->input->post('type'))
        ) {
            redirect('admin/types');
        } else {
            $this->form_validation->set_message('type[name]', 'Cannot create a type with that name.');
            $this->view('admin/types_create'); // custom wrapper for $this->load->view()
        }
    }

The types->create() method returns FALSE if a record already exists with the same name (I have a UNIQUE constraint on the 'name' column in the MySQL database, otherwise it returns the inserted record's PK). In this case, all of the validation rules are being satisfied, but not for uniqueness on the MySQL end.

The above code doesn't, contrary to my expectations, appear to set an error message for the relevant field, or if it does it's not being passed back for display to the validation_errors() or form_error() functions.

Previously I've used callbacks, but I find them clunky and I'd rather take advantage of MySQL's ability to do the heavy lifting to keep the code lean(er).

My question is: do I have to use a callback (and return FALSE that way to get it to force form_validation->run() == FALSE) or is there a way of setting an error message even if all of the defined rules are met?
#2

[eluser]bluematt[/eluser]
I've managed to solve this, at least cosmetically...

My controller now uses a custom $form_validation->set_error() method instead of $form_validation->set_message():

Code:
if ($this->form_validation->run() && $this->types->create($this->input->post('type'))) {
    redirect('admin/types');
} else {
    $this->form_validation->set_error('type[name]', 'Cannot create a type with that %s.');
    $this->view('admin/types_create');
}

And my customised Form_validation class:

Code:
class MY_Form_validation extends CI_Form_validation {

    function __construct($config=array()) {
        parent::__construct($config);
    }

    function set_error($field, $error) {
        // This is checked by $form_validation->error_string()
        $this->_error_array[$field] = sprintf($error, $this->_field_data[$field]['label']);
        // This is checked by $form_validation->error()
        $this->_field_data[$field]['error'] = sprintf($error, $this->_field_data[$field]['label']);
    }

}




Theme © iAndrew 2016 - Forum software by © MyBB