2

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.

2 Answers 2

5

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[]');
Sign up to request clarification or add additional context in comments.

5 Comments

I've done that but if I submit the form without selecting any categories the validation should fail but it doesn't
Ohkk then check your html if its first option should do not have any value e.g. <option value="" selected>select me</option> mark that no space in value :)
@geoffs3310 also you can try $this->form_validation->set_rules('event_categories[]', 'Categories', 'trim|required');
Ahh I've sorted it now, it's because I was using form_error('event_categories') instead of form_error('event_categories[]')
Edited as answer suggested by you :)
0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.