DataTables: how to set configuration after init?

1.1k Views Asked by At

I'm using the WordPress plugin TablePress for tables. It creates DataTables tables which I'd like to modify after init.

Problem: the tables are already initialized by the plugin, which means I can't use the constructor anymore.

// Already set by the plugin:
$('#tablepress-1').dataTable({
    columnDefs: [
        { targets: -1, className: 'dt-body-right'}
    ]
});

I'm looking for something like that (pseudocode):

var table = $('#tablepress-1').dataTable();
table.updateConfig({
    columnDefs: [
        { targets: -1, className: 'dt-body-right'}
    ]
})

Any idea? Thanks!

1

There are 1 best solutions below

0
davidkonrad On BEST ANSWER

It is not so clear exactly what you want to modify. Many options cannot be modified, and to modify for example columnDefs require re-initialisation (which needs destroy: true). If the options you want to modify is generic / static you can extend DataTables defaults:

$.extend( true, $.fn.dataTable.defaults, {
  columnDefs: [
    { targets: '_all', className: 'dt-body-right' } // _all not -1
  ]
})

className and any other default can still be overwritten by the options passed to the constructor. If that is the problem you can "monkey patch" DataTables:

const orgDT = $.fn.DataTable
$.fn.DataTable = function(config) {
   config.columns[0].className += ' table-success'
   return orgDT.call(this, config)
}

This gives 100% control over however this "tablepress" initalise DataTables - the config is simply picked up and can be altered before the table is instantiated.