PHP code example of umer936 / cakephp-datatables

1. Go to this page and download the library: Download umer936/cakephp-datatables library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

umer936 / cakephp-datatables example snippets


// In your controller
$data = $this->DataTables->find(
	'Users',
	'datatables',
	[
		'delegateSearch' => true,
		'delegateOrder' => true,
	],
	$columns
);

// In src/Model/Table/UsersTable.php
use Cake\ORM\Query\SelectQuery;

public function findDatatables(SelectQuery $query, array $options): SelectQuery
{
	$search = $options['globalSearch'] ?? '';
	$requestedOrder = $options['customOrder'] ?? [];

	if ($search !== '') {
		$search = '%' . $search . '%';
		$query->where([
			'OR' => [
				'Users.first_name LIKE' => $search,
				'Users.last_name LIKE' => $search,
			],
		]);
	}

	// Allowlist requested sort keys and map virtual fields to SQL expressions.
	$safeOrder = [];
	foreach ($requestedOrder as $field => $dir) {
		$dir = strtoupper((string)$dir) === 'DESC' ? 'DESC' : 'ASC';

		if ($field === 'full_name') {
			$safeOrder[$query->newExpr("Users.first_name || ' ' || Users.last_name")] = $dir;
			continue;
		}

		if (in_array($field, ['Users.id', 'Users.created'], true)) {
			$safeOrder[$field] = $dir;
		}
	}

	if ($safeOrder) {
		$query->orderBy($safeOrder);
	}

	return $query;
}