Skip to content

DataTable Request Handler

Tigran Gabrielyan edited this page Feb 7, 2015 · 1 revision

A Closer Look At The DataTable Request Handling

<?php
trait DataTableRequestHandlerTrait {

	public function processDataTableRequest() {
		$config = $this->request->query('config');
		if (method_exists($this, $config)) {
			$this->setAction($config);
			return;
		}
		$this->DataTable->paginate($config);
	}
}

The helper will generate a url to /{{controller}}/processDataTableRequest?config={{config_name}}. When a request is made, processDataTableRequest() will first check if the controller has a method with the same name as the config. If it does, it will set the current action to that for custom processing of the request. If an action with the name of the config does not exist, it will paginate the current config automatically.

When is custom processing necessary?

One example would be for a multi-tenant application. You can add a condition to limit results based on the current logged in user.

<?php
App::uses('AppController', 'Controller');
class ArticlesController extends AppController {

	public $components = [
		'DataTable.DataTable' => [
			'limitByUser' = [
				'columns' => [
					'id',
					'title',
					'body',
				],
			],
		],
	];

	public $helpers = [
		'DataTable.DataTable',
	];

	public function index() {
		$this->DataTable->setViewVar('limitByUser');
	}

	public function limitByUser() {
		$this->DataTable->paginate(null, [
			'Article.user_id' => $this->Auth->user('id'),
		]);
	}
}