Reputation: 5829
I have a form with an array field that allows the user to select multiple category ids. They must select at least one category but can select more than one. My form validation needs to ensure at least one category id is specified and then for each category id it needs to check that it is a valid category. Here is what I have:
$this->form_validation->set_rules('event_categories', 'Categories', 'required');
$this->form_validation->set_rules('event_categories[]', 'Categories', 'integer|exists[category.id]');
I have extended the form validation library and added the exists method which looks like this:
/**
* Checks to see if a value exists in database table field
*
* @access public
* @param string
* @param field
* @return bool
*/
public function exists($str, $field)
{
//die("fe");
list($table, $field)=explode('.', $field);
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
if($query->num_rows() !== 0) {
return TRUE;
}
else {
if(!array_key_exists('exists',$this->_error_messages)) {
$this->CI->form_validation->set_message('exists', "The %s value does not exist");
}
return FALSE;
}
}
The problem is even when I submit a valid array of category ids the form validation fails on the required check and says that I must submit some even though I have.
Upvotes: 2
Views: 9227
Reputation: 2408
From CI DOCS https://www.codeigniter.com/user_guide/libraries/form_validation.html#using-arrays-as-field-names
$this->form_validation->set_rules('event_categories', 'Categories', 'required');
Should be
$this->form_validation->set_rules('event_categories[]', 'Categories', 'required');
To show form error Use
echo form_error('event_categories[]');
Upvotes: 5
Reputation: 5829
Solved this now, it was because I was calling form_error('event_categories')
instead of form_error('event_categories[]')
So just to clarify if you are submitting an array that is required the correct validation rule format is:
$this->form_validation->set_rules('event_categories[]', 'Categories', 'required');
Upvotes: 0