Setting defaultContent globally across all datatables

Viewed 381

I just updated my Datatable library from 1.10.12 to 1.11.4.

I use datatables extensively in my web app and after this upgrade I keep getting this error: https://datatables.net/manual/tech-notes/4 enter image description here

I understand that this warning basically wants me to set a "defaultContent": "" to my column definition. The problem is that I would need to update over 200 tables in the webapp to fix the issue.
Is there a way to set this defaultContent:'' globally ?

I have attempted a few things, but the most recent was to extend the defaults in datatables.js with this code

$.extend(true, $.fn.dataTable.defaults, {
    columnDefs: [
        {
            targets:'_all',
            defaultContent: "",
        },
    ]
});

The problem with that, I think, is that in my tables I do this:

 let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columnDefs: [
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder  // If this is null or undefined that error shows up

            },
            targets: columnCount++
            defaultContent: '' // I DO NOT want to add this to every single column in every table.

        }
    ],
 });

Which overrides the previous definition of the columnDefs.

Similar to this post: datatables default render function for empty cells

So going back to what I am trying to accomplish:
Is there a way to set this defaultContent:'' globally once and have it applied to all columnDefs?

1 Answers

One solution would be to change:

 let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columnDefs: [
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder  // If this is null or undefined that error shows up

            },
            targets: columnCount++
            defaultContent: '' // I DO NOT want to add this to every single column in every table.

        }
    ],
 });

to

 let columnCount = 0
 let table = $("#someTable").DataTable({
    data: [],
    paging: false,
    responsive: true,
    sDom: '<"top"B>rt<"bottom"i><"clear">',
    columns: [ <----- NOTE THIS CHANGE and no defaultContent
        {
            // Order
            render: function (data, type, row) {
                return row.sortOrder 
            },
            targets: columnCount++              
        }
    ],
 });

and have

$.extend(true, $.fn.dataTable.defaults, {
    columnDefs: [
        {
            targets:'_all',
            defaultContent: "",
        },
    ]
});

This would still involve changing part of the datatables but not every single column definition at least.

Related