6

I am having trouble setting up a custom dataTables that uses the Buttons plugin.

I can set up a custom default dom layout that works:

//vanilla dom (frtip...)
$.extend($.fn.dataTable.defaults, {
  dom: 'frtip'
});

But if I try to include the "B" character in the dom layout:

// Invoke Buttons plugin (Bfrtip...)
$.extend($.fn.dataTable.defaults, {
  dom: 'Bfrtip'
});

...then run dataTables, this JavaScript error is reported:

Uncaught TypeError: Cannot read property 'buttons' of undefined

What am I doing wrong?

Please see an example of this at https://jsfiddle.net/jhfrench/at83rcoL/

Jeromy French
  • 11,812
  • 19
  • 76
  • 129

1 Answers1

18

I figured it out while drafting this question. Sharing the hard-won answer here:

It is not enough to just include the relevant JS assets (jquery.dataTables.min.js, dataTables.buttons.min.js, etc). You also have to invoke the Buttons plugin by either extending the defaults with the button object element:

// Invoke Buttons plugin (Bfrtip...)
$.extend($.fn.dataTable.defaults, {
    buttons: [ 'copy', 'csv', 'excel' ]
});

Or you can call it at dataTable() initialization:

$("#table2").DataTable({
  buttons: [
    'copy', 'excel', 'pdf'
  ]
});

See https://jsfiddle.net/jhfrench/at83rcoL/8/ for examples of both approaches working.

Jeromy French
  • 11,812
  • 19
  • 76
  • 129
  • Most of the built-in options for `dom` can be turned off and the `dom` option can still mention them and it won't blow up. Sadly, for the buttons plugin, you either have to omit the `B` if you aren't using buttons on a given DT instance, or ensure that if `B` is in `dom`, that `buttons` is defined in the options. This makes setting a nice default `dom` value sitewide that includes `B` problematic, as it assumes every instance will have buttons. Next time I work on this I'm going to try setting a default of `buttons: false` or `buttons: []` and see if that fixes it. – jinglesthula Nov 09 '17 at 17:10
  • Actually, I just tried it real quick in the above fiddle :) Sure enough, in the fiddle's first example (the one w/o buttons) if you set `dom: 'Bfrtip'` and provide `buttons: []` it works! (`buttons: false` tosses an exception) – jinglesthula Nov 09 '17 at 17:13