So, how do we initiate Datatables when we don’t know what the data will look like beforehand?
Setting up Dynamic Headers for jQuery Datatables
Now that we had an array of the dynamic headers we could create our table and column definitions. The table was built using simple jQuery append methods as we had the tables scaffolding already created in our HTML. It looked something like this:
We had some default columns that needed to be included in the table, but once we had the dynamic values from the database we simply appended them to the row. One thing to note is that we appended the headers to the table before Datatables was ever initialized.
As I mentioned before, the array of values that we retrieved was also used to build the column definitions that Datatables requires to build the table. The function that we used to build out the column definitions looks something like this:
The function that we built for this task is a little more complicated because we had a few of the required columns that we needed to account for. In a situation where all the columns are dynamic, simply looping through the array and creating the objects that Datatables requires for its definitions does the trick.
Now that we had all the definitions defined and a table built, we needed to initialize Datatables. This requires some back-end work so let’s take a look at the Laravel-Datatables functions that we used.
Note: To use this, make sure to turn server-side processing on when initializing Datatables.