Skip to content
Advertisement

Array of columns with a single variable + defaultColumns in Datatables

I’m trying to create dynamic columns in my Datatables.

Suppose I want to create 4 columns + default column (2 buttons). Well, we would do the following (this works):

JavaScript

Now suppose I want to do the SAME thing, but with a single value, something like this:

JavaScript

dataHeader contains the following:

JavaScript

(Is a copy paste from console.log from my browser because I need reputation to upload images).

As all of you can see, it has the same format but it doesn’t show the defaultColumns and I don’t know why. I don’t get any type of error.

Does anyone know if it is possible to do something like this?

This is my full code:

JavaScript

Also, as an additional question, how can I add values in my TH? I mean, add like a title for each column.

Also, as an additional question, how can I add values in my TH? I mean, add like a title for each column.

I tryied to add <tr><td>Test 1</td></tr> in my <thead></thead>, but nothing …

Thank you in advance, guys.

Advertisement

Answer

The problem is happening because the dataHeader variable is an array, so what it actually looks like is this:

JavaScript

Side Note: I simplified your variable because it appears to contain both data and mData options:

JavaScript

Whereas it only needs to contain data options:

JavaScript

mData is the old name for data – so these options are equivalent.


If you take this array and add it into your DataTable, you end up with the following structure for the columns option:

JavaScript

And this is not what you want – you have that extra array inside the columns array. This is not valid for DataTables.

Solution:

You can work around this by taking that HTML string and adding it to the array provided by PHP:

JavaScript

The push() function adds the defaultContent object to the end of the dynamicColumns array.

Now you can use this new variable dynamicColumns in your DataTable:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement