CakePHP 4 Bulk Delete

CakePHP 4 Bulk Delete

This tutorial will show how to create a bulk delete function in CakePHP 4. The bulk delete is a process of selecting a group of records in a single table and remove it from the database. A checkbox will be rendered on each of the record ID and send it to the function that manages the delete all process.


Create Checkbox
File Location: ...\templates\Users\index.php
A checkbox is used to capture the id of each selected record that need to be deleted. The checkbox is generated in the index page as shown below:

<table id="main_index" class="table table-hover text-nowrap">
<thead>
	<tr>
		<th><?= $this->Paginator->sort('#') ?></th>

		...other codes

	<?= $this->Form->create(null,['url'=>['action'=>'bulkDelete']]) ?>
	<?php foreach ($users as $user): ?>
	<tr>
		<td><?= $this->Form->checkbox('ids[]',['value'=>$user->id]) ?></td>
</table>
	<button class="button">Delete Selected</button>
	<?= $this->Form->end() ?>
	<?= $this->fetch('postLink'); ?>




Public Function bulkDelete
Create the public function that handles the bulk delete process as shown below in your controller.
File Location: ...\src\Controller\UsersController.php

public function bulkDelete()
{
	$this->request->allowMethod(['post','delete']);
	$ids = $this->request->getData('ids');
	
	if($this->Users->bulkDelete(['Users.id IN'=>$ids])){
		$this->Flash->success(__('The selected user has been deleted.'));
	} else {
		$this->Flash->error(__('Please select user to delete'));
	}
		return $this->redirect(['action' => 'index']);
		//exit('test');
}


Now you should be able to select and delete the records.

If you want to have a main checkbox in your header that will select  all or deselect all the checkbox with one single click, use this code in your header:

<th><?= $this->Form->checkbox('ids[]',['onchange'=>'checkAll(this)', 'name'=>'chk[]']) ?></th>


Then add the following script at the end of your code:

<script>
 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
 }
</script>


That all. Happy coding :)