Skip to content

Enhancing an existing table

ypnos-web edited this page Oct 24, 2017 · 4 revisions

In the Quick Start example the table is completely populated by DataTables. What if we already have a table and want to merely enhance it?

Table with server-side processing

Here is an example:

<table id="<?=$tableid?>" class="table table-striped table-hover linktable dataTable">
  <thead>
    <tr>
      <th><?=__('First Name')?></th>
      <th><?=__('Last Name')?></th>
      <th><i><?=__('Login name')?></i></th>
      <th><?=__('Department')?></th>
    </tr>
  </thead>
</table>

In this case we have a <thead> element for our table heading, but let DataTables only create the data rows. We could also have a <tbody> element which includes data. DataTables can work with that, however note that with server-side processing, DataTables will always completely replace the content.

Now we can initialize DataTables, and other than in the previous example, we do not need to provide column titles. In the controller:

$columns = [
	[
		'field' => 'Users.id',
		'data' => 'id',
		'visible' => false,
		'searchable' => false,
	],
	[
		'field' => 'Users.firstname',
		'data' => 'firstname'
	],
	[
		'field' => 'Users.lastname',
		'data' => 'lastname'
	],
	[
		'field' => 'Users.username',
		'data' => 'username',
	],
	[
		'field' => 'Departments.name',
		'data' => 'department.name'
	],
];

In the view:

$options = [
	'ajax' => [
		'url' => $this->Url->build() // current controller, action, params
	],
	'data' => $data,
	'deferLoading' => $data->count(), // https://datatables.net/reference/option/deferLoading
	'columns' => $columns // set by the controller as a view variable
	'order' => [3, 'asc'], // order by username
];
echo $this->Html->scriptBlock($this->DataTables->draw("#$tableid", $options));

Static DataTables

In the case that initial data is already present in the table, we remove the data and deferLoading options, but for any sorting/search etc. operations, DataTables would still query the server.

However, we can also go further and remove all other options, but add 'serverSide' => false. This lets DataTables operate only on the client-side, working the data that was initially provided. It can be useful for tables that only show a small amount of data. It would still give all the sorting, searching etc. functionality.

Clone this wiki locally