Dynamic column rendering

Dynamic column rendering

NoBullManNoBullMan Posts: 88Questions: 25Answers: 2

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

  • allanallan Posts: 64,362Questions: 1Answers: 10,627 Site admin

    My question is how do I apply custom rendering columns based on above code?

    Good question. You've got two options:

    1. Look over the columns array and add the render function you want. That might be designated by some property in the JSON, or you might need to detect the data type.
    2. This one is undocumented as of yet, but you can actually do render: ['number'], which is the same as render: 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

Sign In or Register to comment.