Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-select does not retain value after post in codeigniter

I have a form in my application with a multi select. I'm using CI's form helper to build my forms, so the build of the element looks like this:

return form_multiselect('authors[response][]', $faculty->get_all_for_multiselect(), 
                         $pre_selected, $additional_attributes);

This is all well and good if the items are in the database ($pre_selected gets existing responses). However, I'm also running the form through CI's form validation, and when that happens, if validation fails, then the multi select loses the values that had been selected.

I'm sure this is something simple that I'm just over looking, so hopefully someone can help me out here.

Adding more information

The field is marked as required so it is going through the validator (although it will always pass as I'm automatically selecting the current user).

like image 800
Joel Kinzel Avatar asked Aug 09 '26 19:08

Joel Kinzel


1 Answers

(I'm assuming $pre_selected is an array of values?)

You can reset selected values after failed form submit using the $_POST array.

Since you're already using $pre_selected, you should be able to use the following:

return form_multiselect('authors[response][]', $faculty->get_all_for_multiselect(), 
                         array_unique(array_merge($pre_selected, $_POST['response'])), $additional_attributes);
like image 200
greydnls Avatar answered Aug 12 '26 12:08

greydnls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!