skip to Main Content

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


  1. 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 of value 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).

    Login or Signup to reply.
  2. Go further down your link, you will see multiple checkbox example as below:
    Form input

    $options = [
        'Value 1' => 'Label 1',
        'Value 2' => 'Label 2'
    ];
    echo $this->Form->select('field', $options, [
        'multiple' => 'checkbox'
    ]);
    

    Output form as array

    <input name="field" value="" type="hidden">
    <div class="checkbox">
        <label for="field-1">
            <input name="field[]" value="Value 1" id="field-1" type="checkbox">
            Label 1
        </label>
    </div>
    <div class="checkbox">
        <label for="field-2">
            <input name="field[]" value="Value 2" id="field-2" type="checkbox">
            Label 2
        </label>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search