spreaderman
spreaderman

Reputation: 1086

Codeigniter 3/ form_multiselect / Cannot understand how to do validation

I have the following in my view among other fields:

echo form_multiselect('person_tags[]', $options, set_value('person_tags[]'), $atribute_tag);

The above produces a list of tags, as expected. More than one choice can be made from the list, as expected.

When the form is submitted, validation is run as follows;

$this->form_validation->set_rules('person_tags[]', 'Tags', 'required');

If there are other validation errors, the form re-appears with a list of validation errors but, unfortunately, it doesn't repopulate the form_multiselect() with the originally selected items, as expected. Also, I noticed that if I remove the validation rule for person_tags, when there are other errors on the form, person_tags multiselect() repopulations the list with the originally selected items. How is validation supposed to work? It seems to remove or transform the post.

Upvotes: 0

Views: 128

Answers (1)

sauhardnc
sauhardnc

Reputation: 1961

Instead of defining set_value() with name[], try providing it without them. I created a demo and it works for me. See if this works for you as well.

View

<?php 

$attributes = array('method' => 'POST');

echo form_open('home/form', $attributes);

$options = array(
    'small'         => 'Small Shirt',
    'med'           => 'Medium Shirt',
    'large'         => 'Large Shirt',
    'xlarge'        => 'Extra Large Shirt',
);

$attribute_tag = array(
    'class'         => 'some-class',
);

// this is the one you should be paying attention to ↓↓
echo form_multiselect('person_tags[]', $options, set_value('person_tags'), $attribute_tag);

$data = array(
    'type'  => 'text',
    'name'  => 'email',
    'id'    => 'email',
);

echo form_input($data, set_value('email'));

echo form_submit('mysubmit', 'Submit Post!');
echo form_close(); 

?>

Controller

function form(){

    $this->load->library('form_validation');

    $this->form_validation->set_rules('person_tags[]', 'Tags', 'required');
    $this->form_validation->set_rules('email', 'text', 'required');

    if ($this->form_validation->run() == FALSE){    

        $this->load->view('vwHome');

    }else{
        echo 'No validation error'; die;  // save in database(Your logic)
    }
}

TL;DR
Change your current code to-

echo form_multiselect('person_tags[]', $options, set_value('person_tags'), $attribute_tag);

Upvotes: 1

Related Questions