Deleting Multiple selected items from table

cakephp, checkbox, controller

Solution

Your checkbox input should be something like this

echo $this->Form->checkbox('LocalClocks.'.$LocalClock['LocalClock']['id'], array(
  'value' => $LocalClock['LocalClock']['id'],
  'hiddenField' => false
));

This will create a data array that will look like this

array(
  'LocalClocks' => array(
    1 => 1,
    42 => 1
  )
);

And will omit any unchecked ones from the data array because we're not using the hidden field. Finally, just a couple changes to your action

public function deleteSelected()
{
    foreach($this->request->data['LocalClocks'] as $key => $value)
    {
       $this->LocalClock->delete($key);
    }
    $this->redirect($this->referer());
}

I prefer using `Model::delete()` to `Model::deleteAll()` because it runs the callbacks, where `deleteAll` does not.

Finally, your link will actually be a submit button. This will POST the data to the controller.

echo $this->Form->end('Submit');

If you want to use ajax, use the JsHelper to submit it instead. The following creates an Ajax submission that updates the dom element `#mytable` with the results of the action (in this case the referer that you redirect to).

echo $this->Js->submit('Submit', array(
  'update' => '#mytable'
));
echo $this->Form->end();

Problem

In my table I have a column with a check box for each row. I want to be able to delete all the selected items. I found the code from this website and modified it for my own stuff. Link I followed the website's naming convention for the check boxes and it is as follows: ``` <td> <?php echo $this->Form->checkbox('LocalClocks.id.['.$LocalClock['LocalClock']['id'].']', array('value' => $LocalClock['LocalClock']['id'])); ?></td> ``` This is the code in my controller for the deleteSelected() function: ``` public function deleteSelected() { foreach($this->data['LocalClocks'] as $key => $value) { if($value != 0) { $this->LocalClock->del($value); } } $this->redirect($this->referer()); } ``` This is the code for the actual delete button (just in case it is needed): ``` <?php echo $this->Form->postLink('Delete Selected', array('action' => 'deleteSelected'), array('confirm' => 'Are you sure?')); ?> ``` There are a couple things I think might be the problem: - The code was written for an older version of cake, I think the website said 1.3, but I don't know what to update/correct in the existing code to make it work. - The delete button is the same as the one on cakephp's website on the blog tutorial. The only change I made was removing the id of the item to delete, because im not deleting a single item but multiple items. Any help would be great.

Original source