Welcome Guest, Not a member yet? Register   Sign In
set_checkbox() keeping checked state problem
#1

[eluser]andrejmk[/eluser]
I have this code in my view:

Code:
<input type="checkbox" name="test[]" value="1" <?php echo set_checkbox("test[]", "1")
?>>test1

<input type="checkbox" name="test[]" value="2" <?php echo set_checkbox("test[]", "2") ?>>test2

This checkboxes are not required, but some other fields on the form are. I want to keep the values of this checkboxes when I post the form. The values from the checkboxes are in the POST, but the values are not kept when the form loads again after the post (if some of them is checked before the post, I want it to be checked after the post). I also tried set_checkbox("test", "1"), but it didn't work.
#2

[eluser]obiron2[/eluser]
I think you have fallen foul of the $_POST gotcha. If a checkbox is not checked, then it is NOT returned as part of the $_POST array. You may need to ensure that all of your checkboxes have distinct names (i.e. you can't use test[] as the position in the array will change based on the number of boxes that were checked on submission. you need to give them names test_01 test_02 etc..) When validating for them you need to check them using isset() rather than the value. This means that you also need to keep an array of all the 'possible' checkboxes so that you can iterate that array to run the isset() on each one.

#3

[eluser]andrejmk[/eluser]
I've fixed the problem, by seting validation rules for the checkboxes. If you don't have validation, set_checkbox will not work, it will not repopulate the values. Because they are not required, we need to set some meaningless validation like max_length[9999].
#4

[eluser]TheFuzzy0ne[/eluser]
An empty string will suffice:
Code:
$this->form_validation->set_rules('field_name', '', '');
#5

[eluser]andrejmk[/eluser]
Thanks!




Theme © iAndrew 2016 - Forum software by © MyBB