Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repopulating checkboxes in Codeigniter after Unsuccessful Form Validation

I have a problem repopulating a set of checkboxes after an unsuccessful form validation returns the user back to the same form. Dropdown menus and text inputs could be repopulated, but not checkboxes!

Here's a snippet of the code for the checkboxes:

        <td>
            <?php echo form_checkbox('ambience[]', 'casual', set_checkbox('ambience[]', 'casual')); ?> Casual <br />
            <?php echo form_checkbox('ambience[]', 'romantic', set_checkbox('ambience[]', 'romantic')); ?> Romantic <br />
            <?php echo form_checkbox('ambience[]', 'outdoor', set_checkbox('ambience[]')); ?> Outdoor / Alfresco <br />
            <?php echo form_checkbox('ambience[]', 'trendy', set_checkbox('ambience[]')); ?> Hip & Trendy <br />
            <?php echo form_checkbox('ambience[]', 'vibrant', set_checkbox('ambience[]')); ?> Vibrant <br />
            <?php echo form_checkbox('ambience[]', 'up_scale', set_checkbox('ambience[]')); ?> Upscale <br />
        </td>

The code snippet for text input which successfully repopulated is:

<?php echo form_dropdown('price_range', $options, set_value('price_range')); ?>

Any ideas? I'm really confused why set_checkbox does not work as advertised.

like image 941
Nyxynyx Avatar asked Jun 14 '11 01:06

Nyxynyx


3 Answers

In order for set_checkbox to work properly, an actual validation rule needs to be used on that element. I ran into this problem and could not get the value to show on a resubmit until I included:

$this->form_validation->set_rules('checkbox_name', 'checkbox_title', 'trim');

Then, everything worked perfect.

like image 159
ndcisiv Avatar answered Oct 02 '22 16:10

ndcisiv


You set_checkbox calls are wrong. When you're using an array like "ambience[]" in form_checkbox, you don't want to include the square brackets ([]) in your set_checkbox call. The other problem is that set_checkbox requires a second parameter which you've only included in the first 2 checkboxes.

The set_checkbox should always be like this:

set_checkbox('ambience', 'value');

Where 'value' is the second parameter of the form_checkbox call. Like this:

form_checkbox('ambience[]', 'value', set_checkbox('ambience', 'value'));
like image 21
Francois Deschenes Avatar answered Oct 02 '22 14:10

Francois Deschenes


I actually found that it only works if you use like this:

form_checkbox('ambience[]', 'value', set_checkbox('ambience[]', 'value'));

You need the square array brackets on the name for it to work properly.

like image 43
ngl5000 Avatar answered Oct 02 '22 16:10

ngl5000