I am using
$form->input('Model.name', array('multiple'=>'checkbox');
I am trying to base on model data to set certain checkboxes to checked.
How can i do that?
I am using
$form->input('Model.name', array('multiple'=>'checkbox');
I am trying to base on model data to set certain checkboxes to checked.
How can i do that?
cmptrgeekken's solution works for a single checkbox. I'm assuming you're generating a multiple checkboxes, for a HABTM relation or something similar.
You need to pass a array with the values of the elements that are going to be selected to the method, like this:
$options = array(1 => 'ONE', 'TWO', 'THREE');
$selected = array(1, 3);
echo $form->input('Model.name', array('multiple' => 'checkbox', 'options' => $options, 'selected' => $selected));
is going to generate this:
<div class="input select">
<label for="ModelName">Name</label>
<input name="data[Model][name]" value="" type="hidden">
<div class="checkbox">
<input name="data[Model][name][]" checked="checked" value="1" id="ModelName1" type="checkbox">
<label for="ModelName1" class="selected">ONE</label>
</div>
<div class="checkbox">
<input name="data[Model][name][]" value="2" id="ModelName2" type="checkbox">
<label for="ModelName2">TWO</label>
</div>
<div class="checkbox">
<input name="data[Model][name][]" checked="checked" value="3" id="ModelName3" type="checkbox">
<label for="ModelName3" class="selected">THREE</label>
</div>
</div>
The first and third checkbox checked.
Just remember that you're actually working with a multiple select element that is just displayed as a bunch of checkboxes (Which is IMO better because of the usability).
I don't use CakePHP, but according to the docs, it appears as though you should be able to add the option 'checked'=>true:
$form->input('Model.name', array('type'=>'checkbox','checked'=>true));
since that's one of the options of the checkbox function.
$options = array(1 => 'ONE', 'TWO', 'THREE');
$selected = array(1, 3);
echo $form->input('Model.name',
array(
"name"=>$mnus['Aco']['id'],
"type"=>"select",
"multiple"=>"checkbox",
'options' => $options,
'selected' => $selected)
);
this is the correct way for multiple check box and checked option. I am using this in cake1.3 please recheck once on your code it must work.
Its Super Simple
$form->input('field_name', array('type'=>'checkbox','checked'=>true));
That's it.
Documentation: https://book.cakephp.org/3.0/en/views/helpers/form.html
Another way to have a checkbox checked with the "label" right next to it is.
$form->checkbox('Model.name', array('checked'=>'checked'))?> Label
Label can be what ever you want though. example: 21,000-3000, Tire, Human. I am sure you get the idea.
You can also try this for input with single option
$this->Form->input('name', array('type' => 'checkbox', 'default' => 1, 'checked' => 'checked'));