Dynamically assign column headers

Dynamically assign column headers

NoBullManNoBullMan Posts: 91Questions: 26Answers: 2

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:
I have a dataset, based on an Oracle query, where column names and counts might change.
Is there a way to create a jQuery datatable based on this changing dataset?
I don't want to manually add/remove/update column headers as query gets updated.

Dataset is result of a query like this:

select metric,
listagg(case when site_name = 'X' then TS end) X,
listagg(case when site_name = 'Y' then TS end) Y
from whatever;

With dataset looking like:

metric    X    Y
blah      1    4

And later it might have an added column:

select metric,
listagg(case when site_name = 'X' then TS end) X,
listagg(case when site_name = 'Y' then TS end) Y,
listagg(case when site_name = 'Z' then TS end) Z
from whatever;

resulting in:

metric    X    Y    Z
blah      1    4    2

I know I can change column header if I know what it is, like:

$(document).ready(function () {
    vat table = $('#example').DataTable()'

    $('#example thead th:eq(0)').html('new column header');
}

Answers

  • kthorngrenkthorngren Posts: 22,078Questions: 26Answers: 5,087

    Datatables doesn't support dynamically changing the number of columns. Using destroy() will allow for changing the number of columns. See the second example in the docs for one way to do this.

    The columns.title option will allow Datatables to build the header. You can start with just a table tag and define your columns with -option columns.title`.

    Kevin

  • NoBullManNoBullMan Posts: 91Questions: 26Answers: 2

    Thank you Kevin. I figured it out.

    Once I got my dataset through an Ajax call, I used the following to setup columns,

    var columns = [];
    var dataset;
    var theTable;
    
    $.ajax({
        ...
    }).done(function (result) {
        dataset = JSON.parse(result.d);
        columns = [];
        var keys = Object.keys(dataset[0]);
    
        keys.forEach(function (key) {
            column.push({ title: key, data: key });
        )};
        var tableID = "#myTable";    
    
        // Clear table, if exists 
        if (theTable != null) {
            theTable.clear().destroy();
        }
        // Empty HTML
        $(tableID + " tbody").empty();
        $(tableID + " thead").empty();
    
        // Initialize the DataTable
        theTable = $('#myTable').DataTable({
             data: dataset,
             columns: columns
        });
    }).fail(...) {
    });
    

    Just a watered down version.

  • kthorngrenkthorngren Posts: 22,078Questions: 26Answers: 5,087

    Yep, that looks good!

    Kevin

Sign In or Register to comment.