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.