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-times"></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.type == 'date' ) {
576 let rfc3339 = $date_to_rfc3339(value);
577 if ( rfc3339 != 'Invalid Date' ) {
578 built_value = rfc3339;
582 if ( col.datatype !== undefined ) {
583 if (col.datatype == 'related-object') {
584 let query_term = value;
586 if (criteria != 'exact') {
587 query_term = { like: (['contains', 'ends_with'].indexOf(criteria) !== -1 ? '%' : '') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1 ? '%' : '') };
591 [col.related + '.' + col.relatedKey]: col.relatedValue,
592 [col.related + '.' + col.relatedSearchOn]: query_term
595 console.log("datatype %s not supported yet".format(col.datatype));
599 if (col.datatype != 'related-object') {
601 if ( criteria === 'exact' ) {
602 value_part = built_value ? [value, built_value] : value
604 let like = {like: (['contains', 'ends_with'].indexOf(criteria) !== -1?'%':'') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1?'%':'')};
605 value_part = built_value ? [like, built_value] : like;
608 part[!attr.includes('.')?'me.'+attr:attr] = value_part;
616 var filter = data.search.value;
617 // Build query for each column filter
618 var and_query_parameters = settings.aoColumns
619 .filter(function(col) {
620 return col.bSearchable && typeof col.data == 'string' && data.columns[col.idx].search.value != ''
623 var value = data.columns[col.idx].search.value;
624 return build_query(col, value)
627 return ($.isArray(e) ? $.map(e, r) : e);
630 // Build query for the global search filter
631 var or_query_parameters = settings.aoColumns
632 .filter(function(col) {
633 return col.bSearchable && filter != ''
637 return build_query(col, value)
640 return ($.isArray(e) ? $.map(e, r) : e);
643 if ( default_filters ) {
644 let additional_filters = {};
645 for ( f in default_filters ) {
647 if ( typeof(default_filters[f]) === 'function' ) {
648 let val = default_filters[f]();
649 if ( val != undefined && val != "" ) {
653 k = f; v = default_filters[f];
656 // Pass to -or if you want a separate OR clause
657 // It's not the usual DBIC notation!
659 if (v) or_query_parameters.push(v)
660 } else if ( f == '-and' ) {
661 if (v) and_query_parameters.push(v)
663 additional_filters[k] = v;
666 if ( Object.keys(additional_filters).length ) {
667 and_query_parameters.push(additional_filters);
670 query_parameters = and_query_parameters;
671 if ( or_query_parameters.length) {
672 query_parameters.push(or_query_parameters);
675 if(query_parameters.length) {
676 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:{"-and": query_parameters});
677 if(options.header_filter) {
678 options.query_parameters = query_parameters;
680 dataSet.q = query_parameters;
681 delete options.query_parameters;
684 delete options.query_parameters;
687 dataSet._match = options.criteria;
689 if ( data["draw"] !== undefined ) {
690 settings.ajax.headers = { 'x-koha-request-id': data.draw }
693 if(options.columns) {
694 var order = data.order;
695 var orderArray = new Array();
696 order.forEach(function (e,i) {
697 var order_col = e.column;
698 var order_by = options.columns[order_col].data;
699 order_by = order_by.split(':');
700 var order_dir = e.dir == 'asc' ? '+' : '-';
701 Array.prototype.push.apply(orderArray,order_by.map(x => order_dir + (!x.includes('.')?'me.'+x:x)));
703 dataSet._order_by = orderArray.filter((v, i, a) => a.indexOf(v) === i).join(',');
711 function _dt_buttons(params){
712 let included_ids = params.included_ids || [];
713 let settings = params.settings || {};
714 let table_settings = params.table_settings;
716 var exportColumns = ":visible:not(.noExport)";
717 if( settings.hasOwnProperty("exportColumns") ){
718 // A custom buttons configuration has been passed from the page
719 exportColumns = settings["exportColumns"];
722 var export_format = {
723 body: function ( data, row, column, node ) {
724 var newnode = $(node);
726 if ( newnode.find(".noExport").length > 0 ) {
727 newnode = newnode.clone();
728 newnode.find(".noExport").remove();
731 return newnode.text().replace( /\n/g, ' ' ).trim();
735 var export_buttons = [
737 extend: 'excelHtml5',
740 columns: exportColumns,
741 format: export_format
748 columns: exportColumns,
749 format: export_format
756 columns: exportColumns,
757 format: export_format
764 columns: exportColumns,
765 format: export_format
774 className: "dt_button_clear_filter",
775 titleAttr: __("Clear filter"),
777 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
778 action: function ( e, dt, node, config ) {
779 dt.search( "" ).draw("page");
780 node.addClass("disabled");
785 if( included_ids.length > 0 ){
790 columns: included_ids,
791 className: "columns_controls",
792 titleAttr: __("Columns settings"),
793 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
795 columns: exportColumns
803 extend: 'collection',
806 className: "export_controls",
807 titleAttr: __("Export or print"),
808 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
809 buttons: export_buttons
813 if ( table_settings && CAN_user_parameters_manage_column_config ) {
816 className: "dt_button_configure_table",
818 titleAttr: __("Configure table"),
819 text: '<i class="fa fa-lg fa-wrench"></i> <span class="dt-button-text">' + __("Configure") + '</span>',
821 window.location = '/cgi-bin/koha/admin/columns_settings.pl?module=' + table_settings['module'] + '&page=' + table_settings['page'] + '&table=' + table_settings['table'];
830 function _dt_visibility(table_settings, settings){
833 let included_ids = [];
834 if ( table_settings ) {
835 var columns_settings = table_settings['columns'];
836 $(columns_settings).each( function() {
837 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
838 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
839 if ( used_id == -1 ) return;
841 if ( this['is_hidden'] == "1" ) {
842 hidden_ids.push( used_id );
844 if ( this['cannot_be_toggled'] == "0" ) {
845 included_ids.push( used_id );
850 return [hidden_ids, included_ids];
853 function _dt_on_visibility(add_filters, table_node, table_dt){
855 let visible_columns = table_dt.columns().visible();
856 $(table_node).find('thead tr:eq(1) th').each( function (i) {
857 let th_id = $(this).data('th-id');
858 if ( visible_columns[th_id] == false ) {
866 if( typeof columnsInit == 'function' ){
867 // This function can be created separately and used to trigger
868 // an event after the DataTable has loaded AND column visibility
869 // has been updated according to the table's configuration
874 function _dt_add_filters(table_node, table_dt, filters_options = {}) {
875 $(table_node).find('thead tr').clone().appendTo( $(table_node).find('thead') );
877 $(table_node).find('thead tr:eq(1) th').each( function (i) {
878 var is_searchable = table_dt.settings()[0].aoColumns[i].bSearchable;
879 $(this).removeClass('sorting').removeClass("sorting_asc").removeClass("sorting_desc");
880 $(this).data('th-id', i);
881 if ( is_searchable ) {
882 let input_type = 'input';
883 if ( $(this).data('filter') || filters_options.hasOwnProperty(i)) {
884 input_type = 'select'
885 let filter_type = $(this).data('filter');
886 let existing_search = table_dt.column(i).search();
887 let select = $('<select><option value=""></option></select');
889 // FIXME eval here is bad and dangerous, how do we workaround that?
890 if ( !filters_options.hasOwnProperty(i) ) {
891 filters_options[i] = eval(filter_type)
892 } else if ( typeof filters_options[i] === "function" ) {
893 filters_options[i] = filters_options[i]()
895 $(filters_options[i]).each(function(){
896 let o = $('<option value="%s">%s</option>'.format(this._id, this._str));
897 if ( existing_search === this._id ) {
898 o.prop("selected", "selected");
902 $(this).html( select );
904 var title = $(this).text();
905 var existing_search = table_dt.column(i).search();
906 if ( existing_search ) {
907 $(this).html( '<input type="text" value="%s" style="width: 100%" />'.format(existing_search) );
909 var search_title = __("%s search").format(title);
910 $(this).html( '<input type="text" placeholder="%s" style="width: 100%" />'.format(search_title) );
914 var search = $.fn.dataTable.util.throttle( function ( i, val ) {
921 $( input_type, this ).on( 'keyup change', function () {
922 if ( table_dt.column(i).search() !== this.value ) {
923 if ( input_type == "input" ) {
924 search(i, this.value)
928 .search( this.value.length ? '^'+this.value+'$' : '', true, false )
939 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
940 // These keys must not launch filtering
941 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
943 function _dt_add_delay(table_dt, table_node, delay_ms) {
945 delay = (typeof delay == 'undefined') ? 500 : delay;
947 var previousSearch = null;
949 $("#"+table_node.attr('id')+"_wrapper").find(".dataTables_filter input")
951 .bind("keyup", function(event) {
953 if (blacklist_keys.indexOf(event.keyCode) != -1) {
955 } else if ( event.keyCode == '13' ) {
956 table_dt.search($(input).val()).draw();
958 let val = $(input).val();
959 if (previousSearch === null || previousSearch != val){
960 window.clearTimeout(timerId);
961 previousSearch = val;
962 timerId = window.setTimeout(function(){
963 table_dt.search($(input).val()).draw();
975 * Create a new dataTables instance that uses the Koha RESTful API's as a data source
976 * @param {Object} options Please see the dataTables settings documentation for further
978 * @param {string} [options.criteria=contains] A koha specific extension to the dataTables settings block that
979 * allows setting the 'comparison operator' used in searches
980 * Supports `contains`, `starts_with`, `ends_with` and `exact` match
981 * @param {string} [options.columns.*.type Data type the field is stored in so we may impose some additional
982 * manipulation to search strings. Supported types are currenlty 'date'
983 * @param {Object} table_settings The arrayref as returned by TableSettings.GetTableSettings function
984 * available from the columns_settings template toolkit include
985 * @param {Boolean} add_filters Add a filters row as the top row of the table
986 * @param {Object} default_filters Add a set of default search filters to apply at table initialisation
987 * @return {Object} The dataTables instance
989 $.fn.kohaTable = function(options, table_settings, add_filters, default_filters) {
993 // Don't redefine the default initComplete
994 if ( options.initComplete ) {
995 let our_initComplete = options.initComplete;
996 options.initComplete = function(settings, json){
997 our_initComplete(settings, json);
998 dataTablesDefaults.initComplete(settings, json)
1002 settings = $.extend(true, {}, dataTablesDefaults, {
1003 'deferRender': true,
1007 'pagingType': 'full_numbers',
1010 'emptyTable': (options.emptyTable) ? options.emptyTable : __("No data available in table")
1012 'ajax': _dt_default_ajax({default_filters, options}),
1016 let hidden_ids, included_ids;
1017 [hidden_ids, included_ids] = _dt_visibility(table_settings, settings)
1019 settings["buttons"] = _dt_buttons({included_ids, settings, table_settings});
1021 $(".dt_button_clear_filter, .columns_controls, .export_controls, .dt_button_configure_table").tooltip();
1023 if ( add_filters ) {
1024 settings['orderCellsTop'] = true;
1027 if ( table_settings ) {
1028 if ( table_settings.hasOwnProperty('default_display_length') && table_settings['default_display_length'] != null ) {
1029 settings["pageLength"] = table_settings['default_display_length'];
1031 if ( table_settings.hasOwnProperty('default_sort_order') && table_settings['default_sort_order'] != null ) {
1032 settings["order"] = [[ table_settings['default_sort_order'], 'asc' ]];
1036 var table = $(this).dataTable(settings);
1038 var table_dt = table.DataTable();
1039 if ( add_filters ) {
1040 _dt_add_filters(this, table_dt);
1043 table.DataTable().on("column-visibility.dt", function(){_dt_on_visibility(add_filters, table, table_dt);})
1044 .columns( hidden_ids ).visible( false );