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 _dt_add_delay($("#"+tableId));
71 function toggledClearFilter(searchText, tableId){
72 if( searchText == "" ){
73 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
75 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
80 // Return an array of string containing the values of a particular column
81 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
82 // check that we have a column id
83 if ( typeof iColumn == "undefined" ) return new Array();
84 // by default we only wany unique data
85 if ( typeof bUnique == "undefined" ) bUnique = true;
86 // by default we do want to only look at filtered data
87 if ( typeof bFiltered == "undefined" ) bFiltered = true;
88 // by default we do not wany to include empty values
89 if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
90 // list of rows which we're going to loop through
92 // use only filtered rows
93 if (bFiltered == true) aiRows = oSettings.aiDisplay;
95 else aiRows = oSettings.aiDisplayMaster; // all row numbers
98 var asResultData = new Array();
99 for (var i=0,c=aiRows.length; i<c; i++) {
101 var aData = this.fnGetData(iRow);
102 var sValue = aData[iColumn];
103 // ignore empty values?
104 if (bIgnoreEmpty == true && sValue.length == 0) continue;
105 // ignore unique values?
106 else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
107 // else push the value onto the result data array
108 else asResultData.push(sValue);
113 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
114 // These keys must not launch filtering
115 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
117 // Set a filtering delay for global search field
118 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
120 * Inputs: object:oSettings - dataTables settings object - automatically given
121 * integer:iDelay - delay in milliseconds
122 * Usage: $('#example').dataTable().fnSetFilteringDelay(250);
123 * Author: Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
124 * License: GPL v2 or BSD 3 point style
125 * Contact: zygimantas.berziunas /AT\ hotmail.com
129 iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
131 this.each( function ( i ) {
132 $.fn.dataTableExt.iApiIndex = i;
136 sPreviousSearch = null,
137 anControl = $( 'input', _that.fnSettings().aanFeatures.f );
139 anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
141 if (blacklist_keys.indexOf(event.keyCode) != -1) {
143 }else if ( event.keyCode == '13' ) {
144 $.fn.dataTableExt.iApiIndex = i;
145 _that.fnFilter( $(this).val() );
147 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
148 window.clearTimeout(oTimerId);
149 sPreviousSearch = anControl.val();
150 oTimerId = window.setTimeout(function() {
151 $.fn.dataTableExt.iApiIndex = i;
152 _that.fnFilter( anControl.val() );
163 // Add a filtering delay on general search and on all input (with a class 'filter')
164 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
166 this.fnSetFilteringDelay(iDelay);
167 var filterTimerId = null;
168 $(table).find("input."+sClass).keyup(function(event) {
169 if (blacklist_keys.indexOf(event.keyCode) != -1) {
171 }else if ( event.keyCode == '13' ) {
172 table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
174 window.clearTimeout(filterTimerId);
176 filterTimerId = window.setTimeout(function() {
177 table.fnFilter($(input).val(), $(input).attr('data-column_num'));
181 $(table).find("select."+sClass).on('change', function() {
182 table.fnFilter($(this).val(), $(this).attr('data-column_num'));
186 // Sorting on html contains
187 // <a href="foo.pl">bar</a> sort on 'bar'
188 function dt_overwrite_html_sorting_localeCompare() {
189 jQuery.fn.dataTableExt.oSort['html-asc'] = function(a,b) {
190 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
191 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
192 if (typeof(a.localeCompare == "function")) {
193 return a.localeCompare(b);
195 return (a > b) ? 1 : ((a < b) ? -1 : 0);
199 jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
200 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
201 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
202 if(typeof(b.localeCompare == "function")) {
203 return b.localeCompare(a);
205 return (b > a) ? 1 : ((b < a) ? -1 : 0);
209 jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
210 var x = a.replace( /<.*?>/g, "" );
211 var y = b.replace( /<.*?>/g, "" );
214 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
217 jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
218 var x = a.replace( /<.*?>/g, "" );
219 var y = b.replace( /<.*?>/g, "" );
222 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
226 $.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
227 var x = a.replace( /<.*?>/g, "" );
228 var y = b.replace( /<.*?>/g, "" );
231 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
234 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
235 var x = a.replace( /<.*?>/g, "" );
236 var y = b.replace( /<.*?>/g, "" );
239 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
245 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
246 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
247 * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
248 * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
250 function naturalSort (a, b) {
251 var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
252 sre = /(^[ ]*|[ ]*$)/g,
253 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
254 hre = /^0x[0-9a-f]+$/i,
256 // convert all to strings and trim()
257 x = a.toString().replace(sre, '') || '',
258 y = b.toString().replace(sre, '') || '',
260 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
261 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
262 // numeric, hex or date detection
263 xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
264 yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
265 // first try and sort Hex codes or Dates
267 if ( xD < yD ) return -1;
268 else if ( xD > yD ) return 1;
269 // natural sorting through split numeric strings and default strings
270 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
271 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
272 var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
273 var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
274 // handle numeric vs string comparison - number < string - (Kyle Adams)
275 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
276 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
277 else if (typeof oFxNcL !== typeof oFyNcL) {
281 if (oFxNcL < oFyNcL) return -1;
282 if (oFxNcL > oFyNcL) return 1;
287 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
288 "natural-asc": function ( a, b ) {
289 return naturalSort(a,b);
292 "natural-desc": function ( a, b ) {
293 return naturalSort(a,b) * -1;
299 /* Plugin to allow sorting on data stored in a span's title attribute
301 * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
303 * In DataTables config:
305 * { "sType": "title-string" },
307 * http://datatables.net/plug-ins/sorting#hidden_title_string
309 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
310 "title-string-pre": function ( a ) {
311 var m = a.match(/title="(.*?)"/);
312 if ( null !== m && m.length ) {
313 return m[1].toLowerCase();
318 "title-string-asc": function ( a, b ) {
319 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
322 "title-string-desc": function ( a, b ) {
323 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
329 /* Plugin to allow text sorting to ignore articles
331 * In DataTables config:
333 * { "sType": "anti-the" },
335 * Based on the plugin found here:
336 * http://datatables.net/plug-ins/sorting#anti_the
337 * Modified to exclude HTML tags from sorting
338 * Extended to accept a string of space-separated articles
339 * from a configuration file (in English, "a," "an," and "the")
342 var config_exclude_articles_from_sort = __('a an the');
343 if (config_exclude_articles_from_sort){
344 var articles = config_exclude_articles_from_sort.split(" ");
346 for(i=0;i<articles.length;i++){
347 rpattern += "^" + articles[i] + " ";
348 if(i < articles.length - 1){ rpattern += "|"; }
350 var re = new RegExp(rpattern, "i");
353 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
354 "anti-the-pre": function ( a ) {
355 var x = String(a).replace( /<[\s\S]*?>/g, "" );
357 var z = y.replace(re, "").toLowerCase();
361 "anti-the-asc": function ( a, b ) {
362 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
365 "anti-the-desc": function ( a, b ) {
366 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
372 // Remove string between NSB NSB characters
373 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
374 var pattern = new RegExp("\x88.*\x89");
375 a = a.replace(pattern, "");
376 b = b.replace(pattern, "");
377 return (a > b) ? 1 : ((a < b) ? -1 : 0);
379 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
380 var pattern = new RegExp("\x88.*\x89");
381 a = a.replace(pattern, "");
382 b = b.replace(pattern, "");
383 return (b > a) ? 1 : ((b < a) ? -1 : 0);
386 /* Define two custom functions (asc and desc) for basket callnumber sorting */
387 jQuery.fn.dataTableExt.oSort['callnumbers-asc'] = function(x,y) {
388 var x_array = x.split("<div>");
389 var y_array = y.split("<div>");
391 /* Pop the first elements, they are empty strings */
395 x_array = jQuery.map( x_array, function( a ) {
396 return parse_callnumber( a );
398 y_array = jQuery.map( y_array, function( a ) {
399 return parse_callnumber( a );
408 if ( !x ) { x = ""; }
409 if ( !y ) { y = ""; }
411 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
414 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
415 var x_array = x.split("<div>");
416 var y_array = y.split("<div>");
418 /* Pop the first elements, they are empty strings */
422 x_array = jQuery.map( x_array, function( a ) {
423 return parse_callnumber( a );
425 y_array = jQuery.map( y_array, function( a ) {
426 return parse_callnumber( a );
435 if ( !x ) { x = ""; }
436 if ( !y ) { y = ""; }
438 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
441 function parse_callnumber ( html ) {
442 var array = html.split('<span class="callnumber">');
444 array = array[1].split('</span>');
451 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
452 function footer_column_sum( api, column_numbers ) {
453 // Remove the formatting to get integer data for summation
454 var intVal = function ( i ) {
455 if ( typeof i === 'number' ) {
456 if ( isNaN(i) ) return 0;
458 } else if ( typeof i === 'string' ) {
459 var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
460 if ( isNaN(value) ) return 0;
467 for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
468 var column_number = column_numbers[indice];
471 var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
472 var budgets_totaled = [];
473 $(cells).each(function(){ budgets_totaled.push( $(this).data('self_id') ); });
474 $(cells).each(function(){
475 if( $(this).data('parent_id') && $.inArray( $(this).data('parent_id'), budgets_totaled) > -1 ){
478 total += intVal( $(this).html() );
482 total /= 100; // Hard-coded decimal precision
485 $( api.column( column_number ).footer() ).html(total.format_price());
489 function filterDataTable( table, column, term ){
491 table.column( column ).search( term ).draw("page");
493 table.search( term ).draw("page");
497 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
498 if ( settings && settings.jqXHR ) {
499 console.log("Got %s (%s)".format(settings.jqXHR.status, settings.jqXHR.statusText));
500 alert(__("Something went wrong when loading the table.\n%s: %s. \n%s").format(
501 settings.jqXHR.status,
502 settings.jqXHR.statusText,
503 ( settings.jqXHR.responseJSON && settings.jqXHR.responseJSON.errors ) ? settings.jqXHR.responseJSON.errors.map(m => m.message).join("\n") : ''
506 alert(__("Something went wrong when loading the table."));
508 console.log(message);
511 function _dt_default_ajax (params){
512 let default_filters = params.default_filters;
513 let options = params.options;
515 if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
516 options.criteria = options.criteria.toLowerCase();
522 'beforeSend': function(xhr, settings) {
525 xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
528 'dataFilter': function(data, type) {
529 var json = {data: JSON.parse(data)};
530 if (total = this._xhr.getResponseHeader('x-total-count')) {
531 json.recordsTotal = total;
532 json.recordsFiltered = total;
534 if (total = this._xhr.getResponseHeader('x-base-total-count')) {
535 json.recordsTotal = total;
537 if (draw = this._xhr.getResponseHeader('x-koha-request-id')) {
541 return JSON.stringify(json);
543 'data': function( data, settings ) {
544 var length = data.length;
545 var start = data.start;
548 _page: Math.floor(start/length) + 1,
552 function build_query(col, value){
555 var attributes = col.data.split(':');
556 for (var i=0;i<attributes.length;i++){
558 var attr = attributes[i];
559 let criteria = options.criteria;
560 if ( value.match(/^\^(.*)\$$/) ) {
561 value = value.replace(/^\^/, '').replace(/\$$/, '');
564 // escape SQL LIKE special characters %
565 value = value.replace(/(\%|\\)/g, "\\$1");
569 if ( col.type == 'date' ) {
570 let rfc3339 = $date_to_rfc3339(value);
571 if ( rfc3339 != 'Invalid Date' ) {
572 built_value = rfc3339;
576 if ( col.datatype !== undefined ) {
577 if (col.datatype == 'related-object') {
578 let query_term = value;
580 if (criteria != 'exact') {
581 query_term = { like: (['contains', 'ends_with'].indexOf(criteria) !== -1 ? '%' : '') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1 ? '%' : '') };
585 [col.related + '.' + col.relatedKey]: col.relatedValue,
586 [col.related + '.' + col.relatedSearchOn]: query_term
589 console.log("datatype %s not supported yet".format(col.datatype));
593 if (col.datatype != 'related-object') {
595 if ( criteria === 'exact' ) {
596 value_part = built_value ? [value, built_value] : value
598 let like = {like: (['contains', 'ends_with'].indexOf(criteria) !== -1?'%':'') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1?'%':'')};
599 value_part = built_value ? [like, built_value] : like;
602 part[!attr.includes('.')?'me.'+attr:attr] = value_part;
610 var filter = data.search.value;
611 // Build query for each column filter
612 var and_query_parameters = settings.aoColumns
613 .filter(function(col) {
614 return col.bSearchable && typeof col.data == 'string' && data.columns[col.idx].search.value != ''
617 var value = data.columns[col.idx].search.value;
618 return build_query(col, value)
621 return ($.isArray(e) ? $.map(e, r) : e);
624 // Build query for the global search filter
625 var or_query_parameters = settings.aoColumns
626 .filter(function(col) {
627 return col.bSearchable && filter != ''
631 return build_query(col, value)
634 return ($.isArray(e) ? $.map(e, r) : e);
637 if ( default_filters ) {
638 let additional_filters = {};
639 for ( f in default_filters ) {
641 if ( typeof(default_filters[f]) === 'function' ) {
642 let val = default_filters[f]();
643 if ( val != undefined && val != "" ) {
647 k = f; v = default_filters[f];
650 // Pass to -or if you want a separate OR clause
651 // It's not the usual DBIC notation!
653 if (v) or_query_parameters.push(v)
654 } else if ( f == '-and' ) {
655 if (v) and_query_parameters.push(v)
657 additional_filters[k] = v;
660 if ( Object.keys(additional_filters).length ) {
661 and_query_parameters.push(additional_filters);
664 query_parameters = and_query_parameters;
665 if ( or_query_parameters.length) {
666 query_parameters.push(or_query_parameters);
669 if(query_parameters.length) {
670 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:{"-and": query_parameters});
671 if(options.header_filter) {
672 options.query_parameters = query_parameters;
674 dataSet.q = query_parameters;
675 delete options.query_parameters;
678 delete options.query_parameters;
681 dataSet._match = options.criteria;
683 if ( data["draw"] !== undefined ) {
684 settings.ajax.headers = { 'x-koha-request-id': data.draw }
687 if(options.columns) {
688 var order = data.order;
689 var orderArray = new Array();
690 order.forEach(function (e,i) {
691 var order_col = e.column;
692 var order_by = options.columns[order_col].data;
693 order_by = order_by.split(':');
694 var order_dir = e.dir == 'asc' ? '+' : '-';
695 Array.prototype.push.apply(orderArray,order_by.map(x => order_dir + (!x.includes('.')?'me.'+x:x)));
697 dataSet._order_by = orderArray.filter((v, i, a) => a.indexOf(v) === i).join(',');
705 function _dt_buttons(params){
706 let included_ids = params.included_ids || [];
707 let settings = params.settings || {};
708 let table_settings = params.table_settings;
710 var exportColumns = ":visible:not(.noExport)";
711 if( settings.hasOwnProperty("exportColumns") ){
712 // A custom buttons configuration has been passed from the page
713 exportColumns = settings["exportColumns"];
716 var export_format = {
717 body: function ( data, row, column, node ) {
718 var newnode = $(node);
720 if ( newnode.find(".noExport").length > 0 ) {
721 newnode = newnode.clone();
722 newnode.find(".noExport").remove();
725 return newnode.text().replace( /\n/g, ' ' ).trim();
729 var export_buttons = [
731 extend: 'excelHtml5',
734 columns: exportColumns,
735 format: export_format
742 columns: exportColumns,
743 format: export_format
750 columns: exportColumns,
751 format: export_format
758 columns: exportColumns,
759 format: export_format
768 className: "dt_button_clear_filter",
769 titleAttr: __("Clear filter"),
771 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
772 action: function ( e, dt, node, config ) {
773 dt.search( "" ).draw("page");
774 node.addClass("disabled");
779 if( included_ids.length > 0 ){
784 columns: included_ids,
785 className: "columns_controls",
786 titleAttr: __("Columns settings"),
787 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
789 columns: exportColumns
797 extend: 'collection',
800 className: "export_controls",
801 titleAttr: __("Export or print"),
802 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
803 buttons: export_buttons
807 if ( table_settings && CAN_user_parameters_manage_column_config ) {
810 className: "dt_button_configure_table",
812 titleAttr: __("Configure table"),
813 text: '<i class="fa fa-lg fa-wrench"></i> <span class="dt-button-text">' + __("Configure") + '</span>',
815 window.location = '/cgi-bin/koha/admin/columns_settings.pl?module=' + table_settings['module'] + '&page=' + table_settings['page'] + '&table=' + table_settings['table'];
824 function _dt_visibility(table_settings, settings){
827 let included_ids = [];
828 if ( table_settings ) {
829 var columns_settings = table_settings['columns'];
830 $(columns_settings).each( function() {
831 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
832 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
833 if ( used_id == -1 ) return;
835 if ( this['is_hidden'] == "1" ) {
836 hidden_ids.push( used_id );
838 if ( this['cannot_be_toggled'] == "0" ) {
839 included_ids.push( used_id );
844 return [hidden_ids, included_ids];
847 function _dt_on_visibility(add_filters, table_node, table_dt){
849 let visible_columns = table_dt.columns().visible();
850 $(table_node).find('thead tr:eq(1) th').each( function (i) {
851 let th_id = $(this).data('th-id');
852 if ( visible_columns[th_id] == false ) {
860 if( typeof columnsInit == 'function' ){
861 // This function can be created separately and used to trigger
862 // an event after the DataTable has loaded AND column visibility
863 // has been updated according to the table's configuration
868 function _dt_add_filters(table_node, table_dt, filters_options = {}) {
869 $(table_node).find('thead tr').clone().appendTo( $(table_node).find('thead') );
871 $(table_node).find('thead tr:eq(1) th').each( function (i) {
872 var is_searchable = table_dt.settings()[0].aoColumns[i].bSearchable;
873 $(this).removeClass('sorting').removeClass("sorting_asc").removeClass("sorting_desc");
874 $(this).data('th-id', i);
875 if ( is_searchable ) {
876 let input_type = 'input';
877 if ( $(this).data('filter') || filters_options.hasOwnProperty(i)) {
878 input_type = 'select'
879 let filter_type = $(this).data('filter');
880 let existing_search = table_dt.column(i).search();
881 let select = $('<select><option value=""></option></select');
883 // FIXME eval here is bad and dangerous, how do we workaround that?
884 if ( !filters_options.hasOwnProperty(i) ) {
885 filters_options[i] = eval(filter_type)
886 } else if ( typeof filters_options[i] === "function" ) {
887 filters_options[i] = filters_options[i]()
889 $(filters_options[i]).each(function(){
890 let o = $('<option value="%s">%s</option>'.format(this._id, this._str));
891 if ( existing_search === this._id ) {
892 o.prop("selected", "selected");
896 $(this).html( select );
898 var title = $(this).text();
899 var existing_search = table_dt.column(i).search();
900 if ( existing_search ) {
901 $(this).html( '<input type="text" value="%s" style="width: 100%" />'.format(existing_search) );
903 var search_title = __("%s search").format(title);
904 $(this).html( '<input type="text" placeholder="%s" style="width: 100%" />'.format(search_title) );
908 $( input_type, this ).on( 'keyup change', function () {
909 if ( table_dt.column(i).search() !== this.value ) {
910 if ( input_type == "input" ) {
913 .search( this.value )
918 .search( this.value.length ? '^'+this.value+'$' : '', true, false )
929 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
930 // These keys must not launch filtering
931 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
933 function _dt_add_delay(table_node, delay_ms) {
935 let dt = table_node.DataTable();
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 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 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 settings documentation for further
969 * @param {string} [options.criteria=contains] A koha specific extension to the dataTables settings block that
970 * allows setting the 'comparison operator' used in searches
971 * Supports `contains`, `starts_with`, `ends_with` and `exact` match
972 * @param {string} [options.columns.*.type Data type the field is stored in so we may impose some additional
973 * manipulation to search strings. Supported types are currenlty 'date'
974 * @param {Object} table_settings The arrayref as returned by TableSettings.GetTableSettings function
975 * available from the columns_settings template toolkit include
976 * @param {Boolean} add_filters Add a filters row as the top row of the table
977 * @param {Object} default_filters Add a set of default search filters to apply at table initialisation
978 * @return {Object} The dataTables instance
980 $.fn.kohaTable = function(options, table_settings, add_filters, default_filters) {
984 // Don't redefine the default initComplete
985 if ( options.initComplete ) {
986 let our_initComplete = options.initComplete;
987 options.initComplete = function(settings, json){
988 our_initComplete(settings, json);
989 dataTablesDefaults.initComplete(settings, json)
993 settings = $.extend(true, {}, dataTablesDefaults, {
998 'pagingType': 'full_numbers',
1001 'emptyTable': (options.emptyTable) ? options.emptyTable : __("No data available in table")
1003 'ajax': _dt_default_ajax({default_filters, options}),
1007 let hidden_ids, included_ids;
1008 [hidden_ids, included_ids] = _dt_visibility(table_settings, settings)
1010 settings["buttons"] = _dt_buttons({included_ids, settings, table_settings});
1012 $(".dt_button_clear_filter, .columns_controls, .export_controls, .dt_button_configure_table").tooltip();
1014 if ( add_filters ) {
1015 settings['orderCellsTop'] = true;
1018 if ( table_settings ) {
1019 if ( table_settings.hasOwnProperty('default_display_length') && table_settings['default_display_length'] != null ) {
1020 settings["pageLength"] = table_settings['default_display_length'];
1022 if ( table_settings.hasOwnProperty('default_sort_order') && table_settings['default_sort_order'] != null ) {
1023 settings["order"] = [[ table_settings['default_sort_order'], 'asc' ]];
1027 var table = $(this).dataTable(settings);
1029 var table_dt = table.DataTable();
1030 if ( add_filters ) {
1031 _dt_add_filters(this, table_dt);
1034 table.DataTable().on("column-visibility.dt", function(){_dt_on_visibility(add_filters, table, table_dt);})
1035 .columns( hidden_ids ).visible( false );