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 $(this).on( 'search.dt', function ( e, settings ) {
62 toggledClearFilter(settings.oPreviousSearch.sSearch, tableId);
66 let table_node = $("#" + tableId);
67 if ( typeof this.api === 'function' ) {
68 _dt_add_delay(this.api(), table_node);
70 let dt = $(table_node).DataTable();
71 _dt_add_delay(dt, table_node);
77 function toggledClearFilter(searchText, tableId){
78 if( searchText == "" ){
79 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
81 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
86 // Return an array of string containing the values of a particular column
87 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
88 // check that we have a column id
89 if ( typeof iColumn == "undefined" ) return new Array();
90 // by default we only wany unique data
91 if ( typeof bUnique == "undefined" ) bUnique = true;
92 // by default we do want to only look at filtered data
93 if ( typeof bFiltered == "undefined" ) bFiltered = true;
94 // by default we do not wany to include empty values
95 if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
96 // list of rows which we're going to loop through
98 // use only filtered rows
99 if (bFiltered == true) aiRows = oSettings.aiDisplay;
101 else aiRows = oSettings.aiDisplayMaster; // all row numbers
104 var asResultData = new Array();
105 for (var i=0,c=aiRows.length; i<c; i++) {
107 var aData = this.fnGetData(iRow);
108 var sValue = aData[iColumn];
109 // ignore empty values?
110 if (bIgnoreEmpty == true && sValue.length == 0) continue;
111 // ignore unique values?
112 else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
113 // else push the value onto the result data array
114 else asResultData.push(sValue);
119 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
120 // These keys must not launch filtering
121 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
123 // Set a filtering delay for global search field
124 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
126 * Inputs: object:oSettings - dataTables settings object - automatically given
127 * integer:iDelay - delay in milliseconds
128 * Usage: $('#example').dataTable().fnSetFilteringDelay(250);
129 * Author: Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
130 * License: GPL v2 or BSD 3 point style
131 * Contact: zygimantas.berziunas /AT\ hotmail.com
135 iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
137 this.each( function ( i ) {
138 $.fn.dataTableExt.iApiIndex = i;
142 sPreviousSearch = null,
143 anControl = $( 'input', _that.fnSettings().aanFeatures.f );
145 anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
147 if (blacklist_keys.indexOf(event.keyCode) != -1) {
149 }else if ( event.keyCode == '13' ) {
150 $.fn.dataTableExt.iApiIndex = i;
151 _that.fnFilter( $(this).val() );
153 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
154 window.clearTimeout(oTimerId);
155 sPreviousSearch = anControl.val();
156 oTimerId = window.setTimeout(function() {
157 $.fn.dataTableExt.iApiIndex = i;
158 _that.fnFilter( anControl.val() );
169 // Add a filtering delay on general search and on all input (with a class 'filter')
170 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
172 this.fnSetFilteringDelay(iDelay);
173 var filterTimerId = null;
174 $(table).find("input."+sClass).keyup(function(event) {
175 if (blacklist_keys.indexOf(event.keyCode) != -1) {
177 }else if ( event.keyCode == '13' ) {
178 table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
180 window.clearTimeout(filterTimerId);
182 filterTimerId = window.setTimeout(function() {
183 table.fnFilter($(input).val(), $(input).attr('data-column_num'));
187 $(table).find("select."+sClass).on('change', function() {
188 table.fnFilter($(this).val(), $(this).attr('data-column_num'));
192 // Sorting on html contains
193 // <a href="foo.pl">bar</a> sort on 'bar'
194 function dt_overwrite_html_sorting_localeCompare() {
195 jQuery.fn.dataTableExt.oSort['html-asc'] = function(a,b) {
196 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
197 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
198 if (typeof(a.localeCompare == "function")) {
199 return a.localeCompare(b);
201 return (a > b) ? 1 : ((a < b) ? -1 : 0);
205 jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
206 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
207 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
208 if(typeof(b.localeCompare == "function")) {
209 return b.localeCompare(a);
211 return (b > a) ? 1 : ((b < a) ? -1 : 0);
215 jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
216 var x = a.replace( /<.*?>/g, "" );
217 var y = b.replace( /<.*?>/g, "" );
220 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
223 jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
224 var x = a.replace( /<.*?>/g, "" );
225 var y = b.replace( /<.*?>/g, "" );
228 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
232 $.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
233 var x = a.replace( /<.*?>/g, "" );
234 var y = b.replace( /<.*?>/g, "" );
237 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
240 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
241 var x = a.replace( /<.*?>/g, "" );
242 var y = b.replace( /<.*?>/g, "" );
245 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
251 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
252 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
253 * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
254 * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
256 function naturalSort (a, b) {
257 var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
258 sre = /(^[ ]*|[ ]*$)/g,
259 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
260 hre = /^0x[0-9a-f]+$/i,
262 // convert all to strings and trim()
263 x = a.toString().replace(sre, '') || '',
264 y = b.toString().replace(sre, '') || '',
266 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
267 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
268 // numeric, hex or date detection
269 xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
270 yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
271 // first try and sort Hex codes or Dates
273 if ( xD < yD ) return -1;
274 else if ( xD > yD ) return 1;
275 // natural sorting through split numeric strings and default strings
276 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
277 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
278 var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
279 var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
280 // handle numeric vs string comparison - number < string - (Kyle Adams)
281 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
282 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
283 else if (typeof oFxNcL !== typeof oFyNcL) {
287 if (oFxNcL < oFyNcL) return -1;
288 if (oFxNcL > oFyNcL) return 1;
293 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
294 "natural-asc": function ( a, b ) {
295 return naturalSort(a,b);
298 "natural-desc": function ( a, b ) {
299 return naturalSort(a,b) * -1;
305 /* Plugin to allow sorting on data stored in a span's title attribute
307 * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
309 * In DataTables config:
311 * { "sType": "title-string" },
313 * http://datatables.net/plug-ins/sorting#hidden_title_string
315 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
316 "title-string-pre": function ( a ) {
317 var m = a.match(/title="(.*?)"/);
318 if ( null !== m && m.length ) {
319 return m[1].toLowerCase();
324 "title-string-asc": function ( a, b ) {
325 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
328 "title-string-desc": function ( a, b ) {
329 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
335 /* Plugin to allow text sorting to ignore articles
337 * In DataTables config:
339 * { "sType": "anti-the" },
341 * Based on the plugin found here:
342 * http://datatables.net/plug-ins/sorting#anti_the
343 * Modified to exclude HTML tags from sorting
344 * Extended to accept a string of space-separated articles
345 * from a configuration file (in English, "a," "an," and "the")
348 var config_exclude_articles_from_sort = __('a an the');
349 if (config_exclude_articles_from_sort){
350 var articles = config_exclude_articles_from_sort.split(" ");
352 for(i=0;i<articles.length;i++){
353 rpattern += "^" + articles[i] + " ";
354 if(i < articles.length - 1){ rpattern += "|"; }
356 var re = new RegExp(rpattern, "i");
359 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
360 "anti-the-pre": function ( a ) {
361 var x = String(a).replace( /<[\s\S]*?>/g, "" );
363 var z = y.replace(re, "").toLowerCase();
367 "anti-the-asc": function ( a, b ) {
368 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
371 "anti-the-desc": function ( a, b ) {
372 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
378 // Remove string between NSB NSB characters
379 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
380 var pattern = new RegExp("\x88.*\x89");
381 a = a.replace(pattern, "");
382 b = b.replace(pattern, "");
383 return (a > b) ? 1 : ((a < b) ? -1 : 0);
385 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
386 var pattern = new RegExp("\x88.*\x89");
387 a = a.replace(pattern, "");
388 b = b.replace(pattern, "");
389 return (b > a) ? 1 : ((b < a) ? -1 : 0);
392 /* Define two custom functions (asc and desc) for basket callnumber sorting */
393 jQuery.fn.dataTableExt.oSort['callnumbers-asc'] = function(x,y) {
394 var x_array = x.split("<div>");
395 var y_array = y.split("<div>");
397 /* Pop the first elements, they are empty strings */
401 x_array = jQuery.map( x_array, function( a ) {
402 return parse_callnumber( a );
404 y_array = jQuery.map( y_array, function( a ) {
405 return parse_callnumber( a );
414 if ( !x ) { x = ""; }
415 if ( !y ) { y = ""; }
417 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
420 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
421 var x_array = x.split("<div>");
422 var y_array = y.split("<div>");
424 /* Pop the first elements, they are empty strings */
428 x_array = jQuery.map( x_array, function( a ) {
429 return parse_callnumber( a );
431 y_array = jQuery.map( y_array, function( a ) {
432 return parse_callnumber( a );
441 if ( !x ) { x = ""; }
442 if ( !y ) { y = ""; }
444 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
447 function parse_callnumber ( html ) {
448 var array = html.split('<span class="callnumber">');
450 array = array[1].split('</span>');
457 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
458 function footer_column_sum( api, column_numbers ) {
459 // Remove the formatting to get integer data for summation
460 var intVal = function ( i ) {
461 if ( typeof i === 'number' ) {
462 if ( isNaN(i) ) return 0;
464 } else if ( typeof i === 'string' ) {
465 var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
466 if ( isNaN(value) ) return 0;
473 for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
474 var column_number = column_numbers[indice];
477 var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
478 var budgets_totaled = [];
479 $(cells).each(function(){ budgets_totaled.push( $(this).data('self_id') ); });
480 $(cells).each(function(){
481 if( $(this).data('parent_id') && $.inArray( $(this).data('parent_id'), budgets_totaled) > -1 ){
484 total += intVal( $(this).html() );
488 total /= 100; // Hard-coded decimal precision
491 $( api.column( column_number ).footer() ).html(total.format_price());
495 function filterDataTable( table, column, term ){
497 table.column( column ).search( term ).draw("page");
499 table.search( term ).draw("page");
503 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
504 if ( settings && settings.jqXHR ) {
505 console.log("Got %s (%s)".format(settings.jqXHR.status, settings.jqXHR.statusText));
506 alert(__("Something went wrong when loading the table.\n%s: %s. \n%s").format(
507 settings.jqXHR.status,
508 settings.jqXHR.statusText,
509 ( settings.jqXHR.responseJSON && settings.jqXHR.responseJSON.errors ) ? settings.jqXHR.responseJSON.errors.map(m => m.message).join("\n") : ''
512 alert(__("Something went wrong when loading the table."));
514 console.log(message);
517 function _dt_default_ajax (params){
518 let default_filters = params.default_filters;
519 let options = params.options;
521 if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
522 options.criteria = options.criteria.toLowerCase();
528 'beforeSend': function(xhr, settings) {
531 xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
534 'dataFilter': function(data, type) {
535 var json = {data: JSON.parse(data)};
536 if (total = this._xhr.getResponseHeader('x-total-count')) {
537 json.recordsTotal = total;
538 json.recordsFiltered = total;
540 if (total = this._xhr.getResponseHeader('x-base-total-count')) {
541 json.recordsTotal = total;
543 if (draw = this._xhr.getResponseHeader('x-koha-request-id')) {
547 return JSON.stringify(json);
549 'data': function( data, settings ) {
550 var length = data.length;
551 var start = data.start;
554 _page: Math.floor(start/length) + 1,
558 function build_query(col, value){
561 var attributes = col.data.split(':');
562 for (var i=0;i<attributes.length;i++){
564 var attr = attributes[i];
565 let criteria = options.criteria;
566 if ( value.match(/^\^(.*)\$$/) ) {
567 value = value.replace(/^\^/, '').replace(/\$$/, '');
570 // escape SQL LIKE special characters %
571 value = value.replace(/(\%|\\)/g, "\\$1");
575 if ( col.datatype !== undefined ) {
576 if ( col.datatype == 'date' ) {
577 let rfc3339 = $date_to_rfc3339(value);
578 if ( rfc3339 != 'Invalid Date' ) {
579 built_value = rfc3339;
582 else if (col.datatype == 'related-object') {
583 let query_term = value;
585 if (criteria != 'exact') {
586 query_term = { like: (['contains', 'ends_with'].indexOf(criteria) !== -1 ? '%' : '') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1 ? '%' : '') };
590 [col.related + '.' + col.relatedKey]: col.relatedValue,
591 [col.related + '.' + col.relatedSearchOn]: query_term
594 console.log("datatype %s not supported yet".format(col.datatype));
598 if (col.datatype != 'related-object') {
600 if ( criteria === 'exact' ) {
601 value_part = built_value ? [value, built_value] : value
603 let like = {like: (['contains', 'ends_with'].indexOf(criteria) !== -1?'%':'') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1?'%':'')};
604 value_part = built_value ? [like, built_value] : like;
607 part[!attr.includes('.')?'me.'+attr:attr] = value_part;
615 var filter = data.search.value;
616 // Build query for each column filter
617 var and_query_parameters = settings.aoColumns
618 .filter(function(col) {
619 return col.bSearchable && typeof col.data == 'string' && data.columns[col.idx].search.value != ''
622 var value = data.columns[col.idx].search.value;
623 return build_query(col, value)
626 return ($.isArray(e) ? $.map(e, r) : e);
629 // Build query for the global search filter
630 var or_query_parameters = settings.aoColumns
631 .filter(function(col) {
632 return col.bSearchable && filter != ''
636 return build_query(col, value)
639 return ($.isArray(e) ? $.map(e, r) : e);
642 if ( default_filters ) {
643 let additional_filters = {};
644 for ( f in default_filters ) {
646 if ( typeof(default_filters[f]) === 'function' ) {
647 let val = default_filters[f]();
648 if ( val != undefined && val != "" ) {
652 k = f; v = default_filters[f];
655 // Pass to -or if you want a separate OR clause
656 // It's not the usual DBIC notation!
658 if (v) or_query_parameters.push(v)
659 } else if ( f == '-and' ) {
660 if (v) and_query_parameters.push(v)
662 additional_filters[k] = v;
665 if ( Object.keys(additional_filters).length ) {
666 and_query_parameters.push(additional_filters);
669 query_parameters = and_query_parameters;
670 if ( or_query_parameters.length) {
671 query_parameters.push(or_query_parameters);
674 if(query_parameters.length) {
675 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:{"-and": query_parameters});
676 dataSet.q = query_parameters;
677 delete options.query_parameters;
679 delete options.query_parameters;
682 dataSet._match = options.criteria;
684 if ( data["draw"] !== undefined ) {
685 settings.ajax.headers = { 'x-koha-request-id': data.draw }
688 if(options.columns) {
689 var order = data.order;
690 var orderArray = new Array();
691 order.forEach(function (e,i) {
692 var order_col = e.column;
693 var order_by = options.columns[order_col].data;
694 order_by = order_by.split(':');
695 var order_dir = e.dir == 'asc' ? '+' : '-';
696 Array.prototype.push.apply(orderArray,order_by.map(x => order_dir + (!x.includes('.')?'me.'+x:x)));
698 dataSet._order_by = orderArray.filter((v, i, a) => a.indexOf(v) === i).join(',');
706 function _dt_buttons(params){
707 let included_ids = params.included_ids || [];
708 let settings = params.settings || {};
709 let table_settings = params.table_settings;
711 var exportColumns = ":visible:not(.noExport)";
712 if( settings.hasOwnProperty("exportColumns") ){
713 // A custom buttons configuration has been passed from the page
714 exportColumns = settings["exportColumns"];
717 var export_format = {
718 body: function ( data, row, column, node ) {
719 var newnode = $(node);
721 if ( newnode.find(".noExport").length > 0 ) {
722 newnode = newnode.clone();
723 newnode.find(".noExport").remove();
726 return newnode.text().replace( /\n/g, ' ' ).trim();
730 var export_buttons = [
732 extend: 'excelHtml5',
735 columns: exportColumns,
736 format: export_format
743 columns: exportColumns,
744 format: export_format
751 columns: exportColumns,
752 format: export_format
759 columns: exportColumns,
760 format: export_format
769 className: "dt_button_clear_filter",
770 titleAttr: __("Clear filter"),
772 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
773 action: function ( e, dt, node, config ) {
774 dt.search( "" ).draw("page");
775 node.addClass("disabled");
780 if( included_ids.length > 0 ){
785 columns: included_ids,
786 className: "columns_controls",
787 titleAttr: __("Columns settings"),
788 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
790 columns: exportColumns
798 extend: 'collection',
801 className: "export_controls",
802 titleAttr: __("Export or print"),
803 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
804 buttons: export_buttons
808 if ( table_settings && CAN_user_parameters_manage_column_config ) {
811 className: "dt_button_configure_table",
813 titleAttr: __("Configure table"),
814 text: '<i class="fa fa-lg fa-wrench"></i> <span class="dt-button-text">' + __("Configure") + '</span>',
816 window.location = '/cgi-bin/koha/admin/columns_settings.pl?module=' + table_settings['module'] + '&page=' + table_settings['page'] + '&table=' + table_settings['table'];
825 function _dt_visibility(table_settings, settings){
828 let included_ids = [];
829 if ( table_settings ) {
830 var columns_settings = table_settings['columns'];
831 $(columns_settings).each( function() {
832 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
833 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
834 if ( used_id == -1 ) return;
836 if ( this['is_hidden'] == "1" ) {
837 hidden_ids.push( used_id );
839 if ( this['cannot_be_toggled'] == "0" ) {
840 included_ids.push( used_id );
845 return [hidden_ids, included_ids];
848 function _dt_on_visibility(add_filters, table_node, table_dt){
850 let visible_columns = table_dt.columns().visible();
851 $(table_node).find('thead tr:eq(1) th').each( function (i) {
852 let th_id = $(this).data('th-id');
853 if ( visible_columns[th_id] == false ) {
861 if( typeof columnsInit == 'function' ){
862 // This function can be created separately and used to trigger
863 // an event after the DataTable has loaded AND column visibility
864 // has been updated according to the table's configuration
869 function _dt_add_filters(table_node, table_dt, filters_options = {}) {
870 $(table_node).find('thead tr').clone().appendTo( $(table_node).find('thead') );
872 $(table_node).find('thead tr:eq(1) th').each( function (i) {
873 var is_searchable = table_dt.settings()[0].aoColumns[i].bSearchable;
874 $(this).removeClass('sorting').removeClass("sorting_asc").removeClass("sorting_desc");
875 $(this).data('th-id', i);
876 if ( is_searchable ) {
877 let input_type = 'input';
878 if ( $(this).data('filter') || filters_options.hasOwnProperty(i)) {
879 input_type = 'select'
880 let filter_type = $(this).data('filter');
881 let existing_search = table_dt.column(i).search();
882 let select = $('<select><option value=""></option></select');
884 // FIXME eval here is bad and dangerous, how do we workaround that?
885 if ( !filters_options.hasOwnProperty(i) ) {
886 filters_options[i] = eval(filter_type)
887 } else if ( typeof filters_options[i] === "function" ) {
888 filters_options[i] = filters_options[i]()
890 $(filters_options[i]).each(function(){
891 let o = $('<option value="%s">%s</option>'.format(this._id, this._str));
892 if ( existing_search === this._id ) {
893 o.prop("selected", "selected");
897 $(this).html( select );
899 var title = $(this).text();
900 var existing_search = table_dt.column(i).search();
901 if ( existing_search ) {
902 $(this).html( '<input type="text" value="%s" style="width: 100%" />'.format(existing_search) );
904 var search_title = __("%s search").format(title);
905 $(this).html( '<input type="text" placeholder="%s" style="width: 100%" />'.format(search_title) );
909 $( input_type, this ).on( 'keyup change', function () {
910 if ( table_dt.column(i).search() !== this.value ) {
911 if ( input_type == "input" ) {
914 .search( this.value )
919 .search( this.value.length ? '^'+this.value+'$' : '', true, false )
930 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
931 // These keys must not launch filtering
932 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
934 function _dt_add_delay(table_dt, table_node, delay_ms) {
936 delay = (typeof delay == 'undefined') ? 500 : delay;
938 var previousSearch = null;
940 $("#"+table_node.attr('id')+"_wrapper").find(".dataTables_filter input")
942 .bind("keyup", function(event) {
944 if (blacklist_keys.indexOf(event.keyCode) != -1) {
946 } else if ( event.keyCode == '13' ) {
947 table_dt.search($(input).val()).draw();
949 let val = $(input).val();
950 if (previousSearch === null || previousSearch != val){
951 window.clearTimeout(timerId);
952 previousSearch = val;
953 timerId = window.setTimeout(function(){
954 table_dt.search($(input).val()).draw();
966 * Create a new dataTables instance that uses the Koha RESTful API's as a data source
967 * @param {Object} options Please see the dataTables documentation for further details
968 * We extend the options set with the `criteria` key which allows
969 * the developer to select the match type to be applied during searches
970 * Valid keys are: `contains`, `starts_with`, `ends_with` and `exact`
971 * @param {Object} table_settings The arrayref as returned by TableSettings.GetTableSettings function available
972 * from the columns_settings template toolkit include
973 * @param {Boolean} add_filters Add a filters row as the top row of the table
974 * @param {Object} default_filters Add a set of default search filters to apply at table initialisation
975 * @return {Object} The dataTables instance
977 $.fn.kohaTable = function(options, table_settings, add_filters, default_filters) {
981 // Don't redefine the default initComplete
982 if ( options.initComplete ) {
983 let our_initComplete = options.initComplete;
984 options.initComplete = function(settings, json){
985 our_initComplete(settings, json);
986 dataTablesDefaults.initComplete(settings, json)
990 settings = $.extend(true, {}, dataTablesDefaults, {
995 'pagingType': 'full_numbers',
998 'emptyTable': (options.emptyTable) ? options.emptyTable : __("No data available in table")
1000 'ajax': _dt_default_ajax({default_filters, options}),
1004 let hidden_ids, included_ids;
1005 [hidden_ids, included_ids] = _dt_visibility(table_settings, settings)
1007 settings["buttons"] = _dt_buttons({included_ids, settings, table_settings});
1009 $(".dt_button_clear_filter, .columns_controls, .export_controls, .dt_button_configure_table").tooltip();
1011 if ( add_filters ) {
1012 settings['orderCellsTop'] = true;
1015 if ( table_settings ) {
1016 if ( table_settings.hasOwnProperty('default_display_length') && table_settings['default_display_length'] != null ) {
1017 settings["pageLength"] = table_settings['default_display_length'];
1019 if ( table_settings.hasOwnProperty('default_sort_order') && table_settings['default_sort_order'] != null ) {
1020 settings["order"] = [[ table_settings['default_sort_order'], 'asc' ]];
1024 var table = $(this).dataTable(settings);
1026 var table_dt = table.DataTable();
1027 if ( add_filters ) {
1028 _dt_add_filters(this, table_dt);
1031 table.DataTable().on("column-visibility.dt", function(){_dt_on_visibility(add_filters, table, table_dt);})
1032 .columns( hidden_ids ).visible( false );