-
Notifications
You must be signed in to change notification settings - Fork 24
Callback functions
DataTables allows for several modifications that makes it a very powerful and versatile tool. Many of them use the concept of callback functions*. These functions are passed as parameters in the configuration like you would normally pass a string or a number.
When initializing DataTables through our plugin, you can use the callback()
function for pointing to a Javascript function in three different ways. We use the columns.render
option for our examples.
A simple rendering function that does not need any additional arguments. For example, dt.render.date()
displays the date localized according to the document's lang attribute:
dt.render.date = function (data, type, full, meta)
{
if (type === 'display') {
var date = new Date(data);
return date.toLocaleDateString(document.documentElement.lang);
}
return data;
};
As you can see, it has the signature as described for the columns.render
function type. This is how we would employ it in the options array:
columns => [
[
'title' => __('Last Modified'),
'name' => 'Articles.modified',
'data' => 'modified',
'render' => $this->DataTables->callback('dt.render.date'),
],
…
Note that the date render function is included in the plugin. You can try it right away.
Let's say you have static parameters that you need to provide to the data renderer. An example is the number
renderer as provided by DataTables. You can pass it like this:
columns => [
[
'title' => __('Prize'),
'name' => 'Product.prize',
'data' => 'prize',
'render' => $this->DataTables->callback('$.fn.dataTable.render.number( ',', '.', 2, '$' )'),
],
…
In this scenario, $.fn.dataTable.render.number()
is a function that returns a javascript function with the given parameters as closure variables. DataTables provides more renderers in a plugin.
When writing your own renderers, you might want to keep it simple and instead of a closure just have a signature like this:
dt.render.shorten = function (data, type, full, meta, limit) { … }
Note the additional parameter limit
that we would like to set when setting up the options. We can do so like this:
columns => [
[
'title' => __('Content'),
'name' => 'Article.body',
'data' => 'body',
'render' => $this->DataTables->callback('dt.render.shorten', [50]),
],
…
As you can see, we have an optional second argument to callback()
which must be an array of any arguments to be appended when calling the renderer. Here it is the sole number 50, which maps to our argument limit
in the above signature of dt.render.shorten()
. As arguments are JSON-encoded, you could as well also pass a nested array that contains all kinds of knowledge that your javascript code needs for rendering.
The plugins come with a few generally helpful functions detailed here.