Cakephp 3.6.14: Create table form with checkboxes and process data

I want to create a form where there is an array with a checkbox for each row. So the user can select which rows will be processed in the controller.

So I have created the form and the array. Each row of the array has the name of the Task Elementand a checkbox to select it:

<h3><?= __('Task Elements') ?></h3>
<?php echo $this->Form->create('AddElement', ['url'=>['action' => 'add',$tasktypeid]]); ?>
<table cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th scope="col"><?= $this->Paginator->sort('id') ?></th>
            <th scope="col"><?= $this->Paginator->sort('name') ?></th>
            <th scope="col"><?= $this->Paginator->sort('element_category_id') ?></th>
        </tr>
    </thead>
    <tbody>      
        <?php foreach ($taskElements as $taskElement): ?>      
        <tr>
            <td><?= $this->Number->format($taskElement->id) ?></td>
            <?= $this->Form->hidden('id',['value' => $taskElement->id]); ?>
            <td><?= $this->Form->control(h($taskElement->name), ['type' => 'checkbox']);?></td>
            <td><?= $taskElement->element_category_id != 0 ? $this->Html->link($taskElement->element_category->name, ['controller' => 'ElementCategories', 'action' => 'view', $taskElement->element_category->id]) : '' ?></td>
    &lt;/tr&gt;
    &lt;?php endforeach; ?&gt;            
&lt;/tbody&gt;

</table><?php
echo $this->Form->submit(‘Add’);
echo $this->Form->end();?>

But in the controller debug($this->request->getData()); returns this:

[
‘id’ => ‘32’,
‘Library_Element’ => ‘0’,
‘Library_Element_2’ => ‘0’
]

Which is not correct because ‘Library_Element’ id is 27 not 32. So it should return an array with 2 rows not an array with 1 row and 3 columns.

This is the correct array I am expecting to receive:

Array
(
[0] => Array
(
[id] => 27
[Library_Element] => ‘0’
)

[1] =&gt; Array
    (
        [id] =&gt; 32
        [Library_Element_2] =&gt; '0'
    )

)

Or ideally I would like to get an array like this:

Array
(
[0] => Array
(
[id] => 27
[name] => ‘Library Element’
[checked] => ‘0’
)

[1] =&gt; Array
    (
        [id] =&gt; 32
        [name] =&gt; 'Library Element 2'
        [checked] =&gt; '0'
    )

)

How I can fix that? And then in the controller I want to iterate the POST data and check for each row if it is checked or not. How I can correctly iterate the data ?

#cakephp #php #arrays #forms

5 Likes3.00 GEEK