Reputation: 5395
I've read CakePHP multiple checkbox array HTML the right way but getting strange results. I have a list of tags (from a Model called Tag
). I want to loop through these and output checkboxes for them in a View.
So I have obtained the Tag
data in my Controller with:
$tags = $this->Tag->find('list', ['order' => ['name' => 'ASC']]);
$this->set('tags',$tags);
When I loop through it in my View I am trying to output the checkboxes in between Bootstrap markup:
<?php echo $this->Form->create('GroupTag'); ?>
<?php foreach ($tags as $tag_id => $tag): ?>
<div class="checkbox">
<label>
<?php echo $this->Form->checkbox('tag_id[]', array( 'value'=> $tag_id)); ?>
<?php echo $tag; ?>
</label>
</div>
<?php endforeach; ?>
I copied the syntax for tag_id[]
from the post I linked to.
But when I inspect the markup it's producing the following as the name
attribute for each <input type="checkbox">
:
data[GroupTag][tag_id[]]
Should this not be
data[GroupTag][tag_id][]
?
The idea is that I have multiple checkboxes with a name
attribute tag_id[]
and then in the Controller I can loop through what has been checked.
Please can someone advise on this as I can't get it working and have looked into examples provided on here/docs.
Upvotes: 0
Views: 786
Reputation: 1172
You can also do this:
$this->Form->input('GroupTag.tag_id', [
'type' => 'select',
'multiple' => 'checkbox',
'options' => $tag_id
]);
FormHelper::select(string $fieldName, array $options, array $attributes)
Example:
$options = array(
'Value 1' => 'Label 1',
'Value 2' => 'Label 2'
);
echo $this->Form->select('Model.field', $options, array(
'multiple' => 'checkbox'
));
Output:
<div class="input select">
<label for="ModelField">Field</label>
<input name="data[Model][field]" value="" id="ModelField"
type="hidden">
<div class="checkbox">
<input name="data[Model][field][]" value="Value 1"
id="ModelField1" type="checkbox">
<label for="ModelField1">Label 1</label>
</div>
<div class="checkbox">
<input name="data[Model][field][]" value="Value 2"
id="ModelField2" type="checkbox">
<label for="ModelField2">Label 2</label>
</div>
</div>
Upvotes: -1
Reputation: 1280
Try this
$this->Form->checkbox('tag_id.', array( 'value'=> $tag_id))
Upvotes: 1