How to initialize table without knowing columns at runtime?

How to initialize table without knowing columns at runtime?

tableguytableguy Posts: 5Questions: 3Answers: 0

As a spin-off of this question, I need to know how to initialize my table without knowing the columns.

Here's my code:

var resultsTable = $('#results').DataTable({
    serverSide: true,
    ajax: {
        type: "GET",
        url: "@Url.Content("~/api/search/")" + getEntityType(),
        data: function (data) {
            //Removed for brevity.  See linked question for code
        },
        dataSrc: function (d) {
            //I attempt to set the columns dynamically here, but
            //it doesn't seem to work.  See explanation below
            resultsTable.columns = **getColumnsFromJson(d.Results)**;
            return d.Results;
        }
    }
});

getColumnsFromJson() iterates over all the JSON properties of the first object on the array returned from the server and returns an array of column objects defined like so:

[{ column, title, data, render }]

I know that function works because my table columns are visible when I initialize my table like so:

$('#results').DataTable({
    data: d.Results, //JSON data from server
    columns: getColumnsFromJson(d.Results)
});

Note: In that example, I hardcoded the JSON array from a previous console.log of my full dataset.

Since I don't know the columns at runtime, I cannot initialize my table with columns. When I attempt to run my above code shown in the dataSrc property, I get the following error:

Datables warning: table id=results - Requested unknown parameter '0' for row 0, column 0

My initial table markup looks like this (note the empty THEAD)

<table id="results" class="table table-striped table-bordered" style="background-color:white"><thead></thead></table>

What do I need to do to provide the table with the columns after the table initialization and GET, but before it attempts to populate the table with data?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    You have to know the columns at initialisation time I'm afraid. You can make an Ajax call to the server if you need to be able to configure them, but you cannot dynamically add columns after initialisation.

    See also the "Can I define my columns in Ajax loaded JSON?" FAQ.

    Allan

  • tableguytableguy Posts: 5Questions: 3Answers: 0

    allan, thanks. It turns out that I am fine with this. I was trying to have my server control everything, but I am going to create an API that allows the user to select columns which will get sent to the server anyway, so I will just deliver an EDM to the client which will determine the columns.

This discussion has been closed.