Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables automatically set export title

I got the following .js file which is called on each page of my website and automatically transforms tables to DataTables:

$.extend( $.fn.dataTable.defaults, {
    "buttons": [
        $.extend( true, {}, buttonCommon, {
            extend: 'excelHtml5',
            exportOptions: {
                columns: ':visible'
            }
        } ),
        $.extend( true, {}, buttonCommon, {
            extend: 'pdfHtml5',
            orientation: 'landscape',
            exportOptions: {
                columns: ':visible'
            }
        } ),
        $.extend( true, {}, buttonCommon, {
            extend: 'print',
            exportOptions: {
                columns: ':visible'
            },
            orientation: 'landscape'
        } )
    ]
} );

//Render datatables
$(document).ready(function() {
    if ($('.data-table').length !== 0)
    {
        $('.data-table').DataTable();
    }
});

When I export a table (i.e. excelHtml5, pdfHtml5 or print), I want the exported document's title to display the table's data-exporttitle attribute if the table has such attribute, or else display a default value. Currently and by default, the title displays the page header title.

How can the above script be modified in order to achieve this?

If this info is of any help, some pages on my website contain more than one table.

My first reflex was to add the following "title" line of code in each extend function, but it doesn't work:

$.extend( true, {}, buttonCommon, {
    extend: 'pdfHtml5',
    orientation: 'landscape',
    title: $(this).data("export-title")
} ),
like image 945
Adam Strudwick Avatar asked Oct 24 '25 23:10

Adam Strudwick


1 Answers

You can use buttons.init in the buttonCommon literal. The table reference is a little bit hidden in the params, but it works :

var buttonCommon = {
  init: function(dt, node, config) {
    var table = dt.table().context[0].nTable;
    if (table) config.title = $(table).data('export-title')
  },
  title: 'default title'
};

Now the button exports will have the same title as their associated tables data-export-title attribute.


Usage <table id="example" data-export-title="test">

demo https://jsfiddle.net/d72vmj2h/1/

like image 138
davidkonrad Avatar answered Oct 26 '25 21:10

davidkonrad