Chris Chris - 25 days ago 8
PHP Question

CakePHP: Create array of checkboxes and update field based on whether it's set

I'm not sure if what I'm asking for is possible, but here's the scenario:

I have a foreach() loop that returns some values in HTML format:

<?php foreach($stuff as $s) { ?>
<tr>
<td><?php echo $s['Model']['data']; ?> </td>
</tr>
<?php } ?>


What I need to do is put a checkbox next to each
$s['Model']['data']
, preferably with
$s['Model']['data']
as the label, and be able to set a value in a table based on whether the box is checked. So, my
edit.ctp
would look like this:

<?php foreach($stuff as $s) { ?>
<tr>
<td><?php echo $this->Form->input('flag', array('type'=>'checkbox, 'default'=>'', label=>' $s['Model']['data']', 'value'=>1 )); ?> </td>
</tr>
<?php } ?>


I have no trouble displaying the above. My problem is that I don't know how to tell my controller to update the necessary field if the labeled box is checked. Here's my first run at it:

if($this->request->save($this->request->data)) {
foreach($stuff as $s) {
$this->Model->id = $s['Model']['id'];
if(isset($this->request->data['FormName']['flag'])) {
$this->Model->set('flag', 1);
$this->Model->save('flag', true);
}
}
}


No errors at runtime, but nothing happens. The
flag
field in the Model I need to update remains = 0. I can debug
$stuff
and see data, so I know it's there. I also know that my edit function is hitting the foreach() loop. What might I be missing? Do I need to assign the checkbox a different value or check for whether it's set some other way?

Answer Source

It seems like you need to identify each checkbox to the current item by modifying the name of each checkbox, otherwise it will just use the value of the last checkbox for all the items.

<?php foreach($stuff as $i => $s) { ?>
 <tr>
    <td><?php echo $this->Form->input('flag'.$i, array('type'=>'checkbox, 'default'=>'', label=>' $s['Model']['data']', 'value'=>1 )); ?> </td>
 </tr>
<?php } ?>

Then in the controller look for that specific flag

if($this->request->save($this->request->data)) {
    foreach($stuff as $i => $s) {
        $this->Model->id = $s['Model']['id'];
        if(isset($this->request->data['FormName']['flag'.$i])) {
            $this->Model->set('flag', 1);
            $this->Model->save('flag', true);
        }
    }
} 

Which assumes that ht elements in $stuff are always in the same order.