Dynamic column rendering
Dynamic column rendering

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:
I am creating a datatable dynamically using various datasets as data source.
Something like below where I get the data using various web service calls that return JSON data:
function renderTable(url, params) {
$.ajax({
....
url: url,
data: params
}).done(function(result) {
....
jResult = JSON.parse(result.d);
if (jResult.length > 0) {
// Dynamically extract column names from the data
var columnNames = Object.keys(jResult[0]);
// Define columns for DataTable
var columns = columnNames.map(function (columnName) {
return {
data: columnName,
title: columnName // Use the column name as the title
};
});
if (isDataTable()) { // checks if #centMonDataTable is a defined datatable
$('#centMonDataTable').DataTable().destroy();
$('#centMonDataTable').empty();
}
// Initialize DataTable
tblCentMonData = $("#centMonDataTable").DataTable({
jQueryUI: true,
data: jResult,
columns: columns
});
}
My question is how do I apply custom rendering columns based on above code?
In one dataset, column one might be integer that I would need to apply number formatting; but in the next dataset column one could be a timestamp that I would need to apply moment function to it.
Answers
Good question. You've got two options:
columns
array and add therender
function you want. That might be designated by some property in the JSON, or you might need to detect the data type.render: ['number']
, which is the same asrender: DataTable.render.number()
. The first parameter of the array is the rendering helper name, the following parameters are arguments to pass to the function. The benefit of this is that you can define the rendering function to use in JSON.Allan