Reputation: 40643
Assuming a form with errors, is there a way to get an array of key (the field name) / value (the error message) pairs? For example:
['name'] => 'The name field is required',
['age'] => 'The name must be greater than 18'
If there is no native way to do this, I will extend the form validation library and expose the protected property *_error_array*.
Upvotes: 2
Views: 2592
Reputation: 193
This might be way belated but I want to share a solution that I use that does not involve extending CI form validation library. The question already has an accepted answer but I hope that it will benefit someone else.
Unfortunately, CodeIgniter's $this->form_validation->error_array()
method returns only the errors that emanate from the set_rules()
method. It does not account for the name of the form field that generated the error. However, we can leverage another of CodeIgniter's method $this->form_validation->error()
, which returns the error(s) associated with a particular form field, by passing the name of the field as parameter.
//form validation rules
$this->form_validation->set_rules('f_name', 'First Name', 'trim|required',
['required' => 'First Name is required']
);
$this->form_validation->set_rules('l_name', 'Last Name', 'trim|required',
['required' => 'Last Name is required']
);
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]',
[
'required' => 'Email is required',
'valid_email' => 'Email format is invalid',
'is_unique' => 'Email already exists'
]
);
$error_arr = []; //array to hold the errors
//array of form field names
$field_names= ['f_name', 'l_name', 'email'];
//Iterate through the form fields to build a field=error associative pair.
foreach ($field_names as $field) {
$error = $this->form_validation->error($field);
//field has error?
if (strlen($error)) $error_arr[$field] = $error;
}
//print_r($error_arr);
Upvotes: 0
Reputation: 40643
I ended up extending the core class:
class MY_Form_validation extends CI_Form_validation
{
public function error_array()
{
return $this->_error_array;
}
}
Upvotes: 8