I am using CakePHP 4.3.
According to the documentation, the option value
can be used to set the value of the "value"
HTML attribute.
Here’s my code:
<?php foreach ($items as $item) { ?>
<?= $this->Form->checkbox('add_' . $item->id, [
'id' => 'add_' . $item->id,
'label' => false,
'hiddenField' => false,
'value' => $item->id,
]) ?>
<?php } ?>
And here’s the output on the page:
<input type="checkbox" name="add_1000936" value="1" id="add_1000936">
Of course I get multiple checkboxes because of the foreach, but that’s beside the point. The problem is that all the checkboxes have value "1"
.
While this is what I would expect:
<input type="checkbox" name="add_1000936" value="1000936" id="add_1000936">
Am I doing something wrong here or is CakePHP somehow bugged?
If I do
<?php foreach ($items as $item) { ?>
<input type="checkbox" value="<?= $item->id ?>" name="add_<?= $item->id ?>" id="add_<?= $item->id ?>">
<?php } ?>
instead, I get the correct output.
2
Answers
Checkboxes cannot have a non-bool value. They are either ticked or not.
Use a hidden field if you need to pass data, or better yet, try to keep this out of the view layer if already known before or in controller/model layer.
You also want to rather use
default
instead ofvalue
as the latter fixates it, so it will break the form flow if invalidated (reset to original state), which is not very user friendly (and confusing).Go further down your link, you will see multiple checkbox example as below:
Form input
Output form as array