Cakephp 3 Delete multiple records.

Delete multiple records using cakephp version 3.x  is very easy task. In this blog post I will give an easy example to delete multiple record using cakephp deleteAll() method. Let’s start

For example assume we have a table call tags. If we fetch all data from tags , index.ctp file it will look like below example.

<table cellpadding="0" cellspacing="0">
  <?php foreach ($tags as $tag): ?>
  <tr>
    <td><?= h($tag->name) ?></td>
    <td><?= h($tag->created) ?></td>
  </tr>
  <?php endforeach; ?>
</table>

For delete multiple records we will prepare our index.ctp code like below

<?= $this->Form->create('tags',['action'=>’deleteAll’','type'=>'post']); ?>
<button>Submit</button>
<table cellpadding="0" cellspacing="0">
<?php foreach ($tags as $tag): ?>
    <tr>
        <td><?=$this->Form->checkbox('ids[]', ['value' => $tag->id]);?></td> 
        <td><?= h($tag->name) ?></td>
        <td><?= h($tag->created) ?></td>
    </tr>
<?php endforeach; ?>
</table>
<?= $this->Form->end(); ?>

In above code we have added a form, Form method is post and form action is deleteAll, Here we also added a button for submit request , Notice most important part was add a checkbox with a name which contain an array. So, after select checkbox if you submit this action to deleteAll method , the method will be like below code.

public function deleteAll()
{
    $ids = $this->request->getData('ids');

if($this->Tags->deleteAll(['Tags.id IN' => $ids]))
{
    $this->Flash->success(__('The tags has been deleted.'));
}else{
    $this->Flash->error(__('The tags could not be deleted'));
}
    return $this->redirect(['action' => 'index']);
}

So, What we have did ? First we received the id’s using getData() method. Then we have used deleteAll() method to delete id’s. After delete succeed we have given a flash message “The tags has been deleted.” Then page will redirect to index.ctp file.
That’s It !

Leave a Reply

Your email address will not be published. Required fields are marked *