1 // These default options are for translation but can be used
2 // for any other datatables settings
4 // $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
7 var dataTablesDefaults = {
10 "first" : __('First'),
13 "previous" : __('Previous'),
15 "emptyTable" : __('No data available in table'),
16 "info" : __('Showing _START_ to _END_ of _TOTAL_ entries'),
17 "infoEmpty" : __('No entries to show'),
18 "infoFiltered" : __('(filtered from _MAX_ total entries)'),
19 "lengthMenu" : __('Show _MENU_ entries'),
20 "loadingRecords" : __('Loading...'),
21 "processing" : __('Processing...'),
22 "search" : __('Search:'),
23 "zeroRecords" : __('No matching records found'),
25 "copyTitle" : __('Copy to clipboard'),
26 "copyKeys" : __('Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.'),
28 _: __('Copied %d rows to clipboard'),
29 1: __('Copied one row to clipboard'),
33 "dom": '<"dt-info"i><"top pager"<"table_entries"lp><"table_controls"fB>>tr<"bottom pager"ip>',
36 className: "dt_button_clear_filter",
37 titleAttr: __('Clear filter'),
39 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __('Clear filter') + '</span>',
40 available: function ( dt ) {
41 // The "clear filter" button is made available if this test returns true
42 if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
46 action: function ( e, dt, node ) {
47 dt.search( "" ).draw("page");
48 node.addClass("disabled");
51 "lengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, __('All')]],
54 initComplete: function( settings) {
55 var tableId = settings.nTable.id
56 var state = settings.oLoadedState;
57 state && toggledClearFilter(state.search.search, tableId);
58 // When the DataTables search function is triggered,
59 // enable or disable the "Clear filter" button based on
60 // the presence of a search string
61 $("#" + tableId ).on( 'search.dt', function ( e, settings ) {
62 toggledClearFilter(settings.oPreviousSearch.sSearch, tableId);
67 function toggledClearFilter(searchText, tableId){
68 if( searchText == "" ){
69 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
71 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
76 // Return an array of string containing the values of a particular column
77 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
78 // check that we have a column id
79 if ( typeof iColumn == "undefined" ) return new Array();
80 // by default we only wany unique data
81 if ( typeof bUnique == "undefined" ) bUnique = true;
82 // by default we do want to only look at filtered data
83 if ( typeof bFiltered == "undefined" ) bFiltered = true;
84 // by default we do not wany to include empty values
85 if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
86 // list of rows which we're going to loop through
88 // use only filtered rows
89 if (bFiltered == true) aiRows = oSettings.aiDisplay;
91 else aiRows = oSettings.aiDisplayMaster; // all row numbers
94 var asResultData = new Array();
95 for (var i=0,c=aiRows.length; i<c; i++) {
97 var aData = this.fnGetData(iRow);
98 var sValue = aData[iColumn];
99 // ignore empty values?
100 if (bIgnoreEmpty == true && sValue.length == 0) continue;
101 // ignore unique values?
102 else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
103 // else push the value onto the result data array
104 else asResultData.push(sValue);
109 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
110 // These keys must not launch filtering
111 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
113 // Set a filtering delay for global search field
114 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
116 * Inputs: object:oSettings - dataTables settings object - automatically given
117 * integer:iDelay - delay in milliseconds
118 * Usage: $('#example').dataTable().fnSetFilteringDelay(250);
119 * Author: Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
120 * License: GPL v2 or BSD 3 point style
121 * Contact: zygimantas.berziunas /AT\ hotmail.com
125 iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
127 this.each( function ( i ) {
128 $.fn.dataTableExt.iApiIndex = i;
132 sPreviousSearch = null,
133 anControl = $( 'input', _that.fnSettings().aanFeatures.f );
135 anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
137 if (blacklist_keys.indexOf(event.keyCode) != -1) {
139 }else if ( event.keyCode == '13' ) {
140 $.fn.dataTableExt.iApiIndex = i;
141 _that.fnFilter( $(this).val() );
143 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
144 window.clearTimeout(oTimerId);
145 sPreviousSearch = anControl.val();
146 oTimerId = window.setTimeout(function() {
147 $.fn.dataTableExt.iApiIndex = i;
148 _that.fnFilter( anControl.val() );
159 // Add a filtering delay on general search and on all input (with a class 'filter')
160 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
162 this.fnSetFilteringDelay(iDelay);
163 var filterTimerId = null;
164 $(table).find("input."+sClass).keyup(function(event) {
165 if (blacklist_keys.indexOf(event.keyCode) != -1) {
167 }else if ( event.keyCode == '13' ) {
168 table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
170 window.clearTimeout(filterTimerId);
172 filterTimerId = window.setTimeout(function() {
173 table.fnFilter($(input).val(), $(input).attr('data-column_num'));
177 $(table).find("select."+sClass).on('change', function() {
178 table.fnFilter($(this).val(), $(this).attr('data-column_num'));
182 // Sorting on html contains
183 // <a href="foo.pl">bar</a> sort on 'bar'
184 function dt_overwrite_html_sorting_localeCompare() {
185 jQuery.fn.dataTableExt.oSort['html-asc'] = function(a,b) {
186 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
187 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
188 if (typeof(a.localeCompare == "function")) {
189 return a.localeCompare(b);
191 return (a > b) ? 1 : ((a < b) ? -1 : 0);
195 jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
196 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
197 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
198 if(typeof(b.localeCompare == "function")) {
199 return b.localeCompare(a);
201 return (b > a) ? 1 : ((b < a) ? -1 : 0);
205 jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
206 var x = a.replace( /<.*?>/g, "" );
207 var y = b.replace( /<.*?>/g, "" );
210 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
213 jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
214 var x = a.replace( /<.*?>/g, "" );
215 var y = b.replace( /<.*?>/g, "" );
218 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
222 $.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
223 var x = a.replace( /<.*?>/g, "" );
224 var y = b.replace( /<.*?>/g, "" );
227 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
230 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
231 var x = a.replace( /<.*?>/g, "" );
232 var y = b.replace( /<.*?>/g, "" );
235 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
241 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
242 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
243 * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
244 * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
246 function naturalSort (a, b) {
247 var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
248 sre = /(^[ ]*|[ ]*$)/g,
249 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
250 hre = /^0x[0-9a-f]+$/i,
252 // convert all to strings and trim()
253 x = a.toString().replace(sre, '') || '',
254 y = b.toString().replace(sre, '') || '',
256 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
257 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
258 // numeric, hex or date detection
259 xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
260 yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
261 // first try and sort Hex codes or Dates
263 if ( xD < yD ) return -1;
264 else if ( xD > yD ) return 1;
265 // natural sorting through split numeric strings and default strings
266 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
267 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
268 var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
269 var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
270 // handle numeric vs string comparison - number < string - (Kyle Adams)
271 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
272 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
273 else if (typeof oFxNcL !== typeof oFyNcL) {
277 if (oFxNcL < oFyNcL) return -1;
278 if (oFxNcL > oFyNcL) return 1;
283 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
284 "natural-asc": function ( a, b ) {
285 return naturalSort(a,b);
288 "natural-desc": function ( a, b ) {
289 return naturalSort(a,b) * -1;
295 /* Plugin to allow sorting on data stored in a span's title attribute
297 * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
299 * In DataTables config:
301 * { "sType": "title-string" },
303 * http://datatables.net/plug-ins/sorting#hidden_title_string
305 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
306 "title-string-pre": function ( a ) {
307 var m = a.match(/title="(.*?)"/);
308 if ( null !== m && m.length ) {
309 return m[1].toLowerCase();
314 "title-string-asc": function ( a, b ) {
315 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
318 "title-string-desc": function ( a, b ) {
319 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
325 /* Plugin to allow text sorting to ignore articles
327 * In DataTables config:
329 * { "sType": "anti-the" },
331 * Based on the plugin found here:
332 * http://datatables.net/plug-ins/sorting#anti_the
333 * Modified to exclude HTML tags from sorting
334 * Extended to accept a string of space-separated articles
335 * from a configuration file (in English, "a," "an," and "the")
338 var config_exclude_articles_from_sort = __('a an the');
339 if (config_exclude_articles_from_sort){
340 var articles = config_exclude_articles_from_sort.split(" ");
342 for(i=0;i<articles.length;i++){
343 rpattern += "^" + articles[i] + " ";
344 if(i < articles.length - 1){ rpattern += "|"; }
346 var re = new RegExp(rpattern, "i");
349 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
350 "anti-the-pre": function ( a ) {
351 var x = String(a).replace( /<[\s\S]*?>/g, "" );
353 var z = y.replace(re, "").toLowerCase();
357 "anti-the-asc": function ( a, b ) {
358 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
361 "anti-the-desc": function ( a, b ) {
362 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
368 // Remove string between NSB NSB characters
369 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
370 var pattern = new RegExp("\x88.*\x89");
371 a = a.replace(pattern, "");
372 b = b.replace(pattern, "");
373 return (a > b) ? 1 : ((a < b) ? -1 : 0);
375 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
376 var pattern = new RegExp("\x88.*\x89");
377 a = a.replace(pattern, "");
378 b = b.replace(pattern, "");
379 return (b > a) ? 1 : ((b < a) ? -1 : 0);
382 /* Define two custom functions (asc and desc) for basket callnumber sorting */
383 jQuery.fn.dataTableExt.oSort['callnumbers-asc'] = function(x,y) {
384 var x_array = x.split("<div>");
385 var y_array = y.split("<div>");
387 /* Pop the first elements, they are empty strings */
391 x_array = jQuery.map( x_array, function( a ) {
392 return parse_callnumber( a );
394 y_array = jQuery.map( y_array, function( a ) {
395 return parse_callnumber( a );
404 if ( !x ) { x = ""; }
405 if ( !y ) { y = ""; }
407 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
410 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
411 var x_array = x.split("<div>");
412 var y_array = y.split("<div>");
414 /* Pop the first elements, they are empty strings */
418 x_array = jQuery.map( x_array, function( a ) {
419 return parse_callnumber( a );
421 y_array = jQuery.map( y_array, function( a ) {
422 return parse_callnumber( a );
431 if ( !x ) { x = ""; }
432 if ( !y ) { y = ""; }
434 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
437 function parse_callnumber ( html ) {
438 var array = html.split('<span class="callnumber">');
440 array = array[1].split('</span>');
447 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
448 function footer_column_sum( api, column_numbers ) {
449 // Remove the formatting to get integer data for summation
450 var intVal = function ( i ) {
451 if ( typeof i === 'number' ) {
452 if ( isNaN(i) ) return 0;
454 } else if ( typeof i === 'string' ) {
455 var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
456 if ( isNaN(value) ) return 0;
463 for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
464 var column_number = column_numbers[indice];
467 var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
468 var budgets_totaled = [];
469 $(cells).each(function(){ budgets_totaled.push( $(this).data('self_id') ); });
470 $(cells).each(function(){
471 if( $(this).data('parent_id') && $.inArray( $(this).data('parent_id'), budgets_totaled) > -1 ){
474 total += intVal( $(this).html() );
478 total /= 100; // Hard-coded decimal precision
481 $( api.column( column_number ).footer() ).html(total.format_price());
485 function filterDataTable( table, column, term ){
487 table.column( column ).search( term ).draw("page");
489 table.search( term ).draw("page");
493 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
494 if ( settings && settings.jqXHR ) {
495 console.log("Got %s (%s)".format(settings.jqXHR.status, settings.jqXHR.statusText));
496 alert(__("Something went wrong when loading the table.\n%s: %s. \n%s").format(
497 settings.jqXHR.status,
498 settings.jqXHR.statusText,
499 settings.jqXHR.responseJSON.errors ? settings.jqXHR.responseJSON.errors.map(m => m.message).join("\n") : ''
502 alert(__("Something went wrong when loading the table."));
504 console.log(message);
510 * Create a new dataTables instance that uses the Koha RESTful API's as a data source
511 * @param {Object} options Please see the dataTables documentation for further details
512 * We extend the options set with the `criteria` key which allows
513 * the developer to select the match type to be applied during searches
514 * Valid keys are: `contains`, `starts_with`, `ends_with` and `exact`
515 * @param {Object} table_settings The arrayref as returned by TableSettings.GetTableSettings function available
516 * from the columns_settings template toolkit include
517 * @param {Boolean} add_filters Add a filters row as the top row of the table
518 * @param {Object} default_filters Add a set of default search filters to apply at table initialisation
519 * @return {Object} The dataTables instance
521 $.fn.kohaTable = function(options, table_settings, add_filters, default_filters) {
525 if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
526 options.criteria = options.criteria.toLowerCase();
528 // Don't redefine the default initComplete
529 if ( options.initComplete ) {
530 let our_initComplete = options.initComplete;
531 options.initComplete = function(settings, json){
532 our_initComplete(settings, json);
533 dataTablesDefaults.initComplete(settings, json)
537 settings = $.extend(true, {}, dataTablesDefaults, {
542 'pagingType': 'full_numbers',
545 'emptyTable': (options.emptyTable) ? options.emptyTable : __("No data available in table")
551 'beforeSend': function(xhr, settings) {
554 xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
556 if(options.header_filter && options.query_parameters) {
557 xhr.setRequestHeader('x-koha-query', options.query_parameters);
558 delete options.query_parameters;
561 'dataFilter': function(data, type) {
562 var json = {data: JSON.parse(data)};
563 if (total = this._xhr.getResponseHeader('x-total-count')) {
564 json.recordsTotal = total;
565 json.recordsFiltered = total;
567 if (total = this._xhr.getResponseHeader('x-base-total-count')) {
568 json.recordsTotal = total;
570 if (draw = this._xhr.getResponseHeader('x-koha-request-id')) {
574 return JSON.stringify(json);
576 'data': function( data, settings ) {
577 var length = data.length;
578 var start = data.start;
581 _page: Math.floor(start/length) + 1,
585 function build_query(col, value){
588 var attributes = col.data.split(':');
589 for (var i=0;i<attributes.length;i++){
591 var attr = attributes[i];
592 let criteria = options.criteria;
593 if ( value.match(/^\^(.*)\$$/) ) {
594 value = value.replace(/^\^/, '').replace(/\$$/, '');
597 // escape SQL LIKE special characters % and _
598 value = value.replace(/(\%|\\)/g, "\\$1");
600 part[!attr.includes('.')?'me.'+attr:attr] = criteria === 'exact'
602 : {like: (['contains', 'ends_with'].indexOf(criteria) !== -1?'%':'') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1?'%':'')};
608 var filter = data.search.value;
609 // Build query for each column filter
610 var and_query_parameters = settings.aoColumns
611 .filter(function(col) {
612 return col.bSearchable && typeof col.data == 'string' && data.columns[col.idx].search.value != ''
615 var value = data.columns[col.idx].search.value;
616 return build_query(col, value)
619 return ($.isArray(e) ? $.map(e, r) : e);
622 // Build query for the global search filter
623 var or_query_parameters = settings.aoColumns
624 .filter(function(col) {
625 return col.bSearchable && filter != ''
629 return build_query(col, value)
632 return ($.isArray(e) ? $.map(e, r) : e);
635 if ( default_filters ) {
636 let additional_filters = {};
637 for ( f in default_filters ) {
639 if ( typeof(default_filters[f]) === 'function' ) {
640 let val = default_filters[f]();
641 if ( val != undefined && val != "" ) {
645 k = f; v = default_filters[f];
648 // Pass to -or if you want a separate OR clause
649 // It's not the usual DBIC notation!
651 if (v) or_query_parameters.push(v)
652 } else if ( f == '-and' ) {
653 if (v) and_query_parameters.push(v)
655 additional_filters[k] = v;
658 if ( Object.keys(additional_filters).length ) {
659 and_query_parameters.push(additional_filters);
662 query_parameters = and_query_parameters;
663 if ( or_query_parameters.length) {
664 query_parameters.push(or_query_parameters);
667 if(query_parameters.length) {
668 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:{"-and": query_parameters});
669 if(options.header_filter) {
670 options.query_parameters = query_parameters;
672 dataSet.q = query_parameters;
673 delete options.query_parameters;
676 delete options.query_parameters;
679 dataSet._match = options.criteria;
681 if ( data["draw"] !== undefined ) {
682 settings.ajax.headers = { 'x-koha-request-id': data.draw }
685 if(options.columns) {
686 var order = data.order;
687 var orderArray = new Array();
688 order.forEach(function (e,i) {
689 var order_col = e.column;
690 var order_by = options.columns[order_col].data;
691 order_by = order_by.split(':');
692 var order_dir = e.dir == 'asc' ? '+' : '-';
693 Array.prototype.push.apply(orderArray,order_by.map(x => order_dir + (!x.includes('.')?'me.'+x:x)));
695 dataSet._order_by = orderArray.filter((v, i, a) => a.indexOf(v) === i).join(',');
706 var included_ids = [];
709 if ( table_settings ) {
710 var columns_settings = table_settings['columns'];
711 $(columns_settings).each( function() {
712 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
713 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
714 if ( used_id == -1 ) return;
716 if ( this['is_hidden'] == "1" ) {
717 hidden_ids.push( used_id );
719 if ( this['cannot_be_toggled'] == "0" ) {
720 included_ids.push( used_id );
726 var exportColumns = ":visible:not(.noExport)";
727 if( settings.hasOwnProperty("exportColumns") ){
728 // A custom buttons configuration has been passed from the page
729 exportColumns = settings["exportColumns"];
732 var export_format = {
733 body: function ( data, row, column, node ) {
734 var newnode = $(node);
736 if ( newnode.find(".noExport").length > 0 ) {
737 newnode = newnode.clone();
738 newnode.find(".noExport").remove();
741 return newnode.text().replace( /\n/g, ' ' ).trim();
745 var export_buttons = [
747 extend: 'excelHtml5',
750 columns: exportColumns,
751 format: export_format
758 columns: exportColumns,
759 format: export_format
766 columns: exportColumns,
767 format: export_format
774 columns: exportColumns,
775 format: export_format
780 settings[ "buttons" ] = [
783 className: "dt_button_clear_filter",
784 titleAttr: __("Clear filter"),
786 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
787 action: function ( e, dt, node, config ) {
788 dt.search( "" ).draw("page");
789 node.addClass("disabled");
794 if( included_ids.length > 0 ){
795 settings[ "buttons" ].push(
799 columns: included_ids,
800 className: "columns_controls",
801 titleAttr: __("Columns settings"),
802 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
804 columns: exportColumns
810 settings[ "buttons" ].push(
812 extend: 'collection',
815 className: "export_controls",
816 titleAttr: __("Export or print"),
817 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
818 buttons: export_buttons
822 if ( table_settings && CAN_user_parameters_manage_column_config ) {
823 settings[ "buttons" ].push(
825 className: "dt_button_configure_table",
826 titleAttr: __("Table settings"),
827 text: '<i class="fa fa-lg fa-wrench"></i> <span class="dt-button-text">' + __("Configure") + '</span>',
829 window.location = '/cgi-bin/koha/admin/columns_settings.pl?module=' + table_settings['module'] + '&page=' + table_settings['page'] + '&table=' + table_settings['table'];
835 $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
838 settings['orderCellsTop'] = true;
841 if ( table_settings ) {
842 if ( table_settings.hasOwnProperty('default_display_length') && table_settings['default_display_length'] != null ) {
843 settings["pageLength"] = table_settings['default_display_length'];
845 if ( table_settings.hasOwnProperty('default_sort_order') && table_settings['default_sort_order'] != null ) {
846 settings["order"] = [[ table_settings['default_sort_order'], 'asc' ]];
850 var table = $(this).dataTable(settings);
854 var table_dt = table.DataTable();
856 $(this).find('thead tr').clone().appendTo( $(this).find('thead') );
858 $(this).find('thead tr:eq(1) th').each( function (i) {
859 var is_searchable = table_dt.settings()[0].aoColumns[i].bSearchable;
860 $(this).removeClass('sorting').removeClass("sorting_asc").removeClass("sorting_desc");
861 $(this).data('th-id', i);
862 if ( is_searchable ) {
863 let input_type = 'input';
864 if ( $(this).data('filter') ) {
865 input_type = 'select'
866 let filter_type = $(this).data('filter');
867 var existing_search = table_dt.column(i).search();
868 let select = $('<select><option value=""></option></select');
870 // FIXME eval here is bad and dangerous, how do we workaround that?
871 $(eval(filter_type)).each(function(){
872 let o = $('<option value="%s">%s</option>'.format(this._id, this._str));
873 if ( existing_search === this._id ) {
874 o.prop("selected", "selected");
878 $(this).html( select );
880 var title = $(this).text();
881 var existing_search = table_dt.column(i).search();
882 if ( existing_search ) {
883 $(this).html( '<input type="text" value="%s" style="width: 100%" />'.format(existing_search) );
885 var search_title = _("%s search").format(title);
886 $(this).html( '<input type="text" placeholder="%s" style="width: 100%" />'.format(search_title) );
890 $( input_type, this ).on( 'keyup change', function () {
891 if ( table_dt.column(i).search() !== this.value ) {
892 if ( input_type == "input" ) {
895 .search( this.value )
900 .search( this.value.length ? '^'+this.value+'$' : '', true, false )
911 table.DataTable().on("column-visibility.dt", function(){
913 let visible_columns = table_dt.columns().visible();
914 $(table).find('thead tr:eq(1) th').each( function (i) {
915 let th_id = $(this).data('th-id');
916 if ( visible_columns[th_id] == false ) {
924 if( typeof columnsInit == 'function' ){
925 // This function can be created separately and used to trigger
926 // an event after the DataTable has loaded AND column visibility
927 // has been updated according to the table's configuration
930 }).columns( hidden_ids ).visible( false );