I have checkbox which is created as below in CI:
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1'
));
I also have other fields such as Name which have a required field validation applied. So, when I leave Name as blank and tick the active
checkbox, then it shows error for name. But it removes the check on active checkbox. I want to keep the active checkbox as checked.
I know about a set_checkbox
method in CI, but not sure how to use this in the above. In case of form_input
we simply use set_value
and all is ok. But with set_checkbox
it returns full string checked="checked"
. So when I use the set_checkbox
and form_checkbox
as combined as below, then it doesn't work.
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1',
'checked' => set_checkbox('active', '1')
));
Any idea how to fix this?
The checked attribute on form_checkbox accepts TRUE/FALSE value. A simple comparison to see if the value is set will work.
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1',
'checked' => ( $this->input->post('active') == 1 )
));
The set_checkbox method was not made to be used in this style. It's intended to be use inside existing HTML as per this example from the CI User Guide
<input type="checkbox" name="mycheck" value="1" <?php echo set_checkbox('mycheck', '1'); ?> />
<input type="checkbox" name="mycheck" value="2" <?php echo set_checkbox('mycheck', '2'); ?> />
You can set this as
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1',
'checked' => ($this->input->post('active') && $this->input->post('active') == 1 )
));
IF you Do not use ($this->input->post('active') && ....) in your condition it will throw an error if you do not check this check-box and submit the form.