dolibarr 25.0.0-alpha
ajax.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2007-2015 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
5 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2026 Open-Dsi <support@open-dsi.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * or see https://www.gnu.org/
22 */
23
51function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array(), $moreparams = '')
52{
53 if (empty($minLength)) {
54 $minLength = 1;
55 }
56
57 $dataforrenderITem = 'ui-autocomplete';
58 $dataforitem = 'ui-autocomplete-item';
59 // Allow two constant to use other values for backward compatibility
60 if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) {
61 $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
62 }
63 if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) {
64 $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM');
65 }
66
67 $htmlnamejquery = str_replace('.', '\\\\.', $htmlname);
68
69 // Input search_htmlname is original field
70 // Input htmlname is a second input field used when using ajax autocomplete.
71 $script = '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" '.($moreparams ? $moreparams : '').' />';
72
73 $script .= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
74 $script .= '<script>'."\n";
75 $script .= '$(document).ready(function() {
76 var autoselect = '.((int) $autoselect).';
77 var options = '.json_encode($ajaxoptions).'; /* Option of actions to do after keyup, or after select */
78
79 /* Remove selected id as soon as we type or delete a char (it means old selection is wrong). Use keyup/down instead of change to avoid losing the product id. This is needed only for select of predefined product */
80 $("input#search_'.$htmlnamejquery.'").keydown(function(e) {
81 if (e.keyCode != 9) /* If not "Tab" key */
82 {
83 if (e.keyCode == 13) { return false; } /* disable "ENTER" key useful for barcode readers */
84 console.log("Clear id previously selected for field '.$htmlname.'");
85 $("#'.$htmlnamejquery.'").val("");
86 }
87 });
88
89 // Check options for secondary actions when keyup
90 $("input#search_'.$htmlnamejquery.'").keyup(function() {
91 if ($(this).val().length == 0)
92 {
93 $("#search_'.$htmlnamejquery.'").val("");
94 $("#'.$htmlnamejquery.'").val("").trigger("change");
95 if (options.option_disabled) {
96 $("#" + options.option_disabled).removeAttr("disabled");
97 }
98 if (options.disabled) {
99 $.each(options.disabled, function(key, value) {
100 $("#" + value).removeAttr("disabled");
101 });
102 }
103 if (options.update) {
104 $.each(options.update, function(key, value) {
105 $("#" + key).val("").trigger("change");
106 });
107 }
108 if (options.show) {
109 $.each(options.show, function(key, value) {
110 $("#" + value).hide().trigger("hide");
111 });
112 }
113 if (options.update_textarea) {
114 $.each(options.update_textarea, function(key, value) {
115 if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
116 CKEDITOR.instances[key].setData("");
117 } else {
118 $("#" + key).html("");
119 }
120 });
121 }
122 }
123 });
124
125 // Activate the autocomplete to execute the GET
126 $("input#search_'.$htmlnamejquery.'").autocomplete({
127 source: function( request, response ) {
128 $.get("'.$url.($urloption ? '?'.$urloption : '').'", { "'.str_replace('.', '_', $htmlname).'": request.term }, function(data){
129 if (data != null)
130 {
131 /* If nothing found, show a line that can not be selected (if a label was provided in options.noresultlabel) */
132 if (data.length == 0 && options.noresultlabel) {
133 response([{ label: options.noresultlabel, value: "", id: "", noresult: true }]);
134 return;
135 }
136 response($.map( data, function(item) {
137 console.log("Received answer from ajax GET, we populate array to return to the jquery autocomplete");
138 if (autoselect == 1 && data.length == 1) {
139 $("#search_'.$htmlnamejquery.'").val(item.value);
140 ';
141 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
142 $script .= '
143 // When product has only one price by qty and 1 result, must set data attributes before triggering change
144 $("#'.$htmlname.'").attr("data-pbq", item.pbq);
145 $("#'.$htmlname.'").attr("data-pbqup", item.price_ht);
146 $("#'.$htmlname.'").attr("data-pbqbase", item.pricebasetype);
147 $("#'.$htmlname.'").attr("data-pbqqty", item.qty);
148 $("#'.$htmlname.'").attr("data-pbqpercent", item.discount);
149 ';
150 }
151 $script .= '
152 $("#'.$htmlnamejquery.'").val(item.key).trigger("change");
153 }
154 var label = "";
155 if (item.labelhtml != null) {
156 label = item.labelhtml.toString();
157 } else if (item.label != null) {
158 label = item.label.toString();
159 }
160 var update = {};
161 if (options.update) {
162 $.each(options.update, function(key, value) {
163 update[key] = item[value];
164 });
165 }
166 var textarea = {};
167 if (options.update_textarea) {
168 $.each(options.update_textarea, function(key, value) {
169 textarea[key] = item[value];
170 });
171 }
172
173 return { label: label,
174 value: item.value,
175 id: item.key,
176 disabled: item.disabled,
177 update: update,
178 textarea: textarea,
179 pbq: item.pbq,
180 type: item.type,
181 qty: item.qty,
182 discount: item.discount,
183 pricebasetype: item.pricebasetype,
184 price_ht: item.price_ht,
185 price_ttc: item.price_ttc,
186 price_unit_ht: item.price_unit_ht,
187 price_unit_ht_locale: item.price_unit_ht_locale,
188 multicurrency_code: item.multicurrency_code,
189 multicurrency_unitprice: item.multicurrency_unitprice,
190 description : item.description,
191 ref_customer: item.ref_customer,
192 tva_tx: item.tva_tx,
193 default_vat_code: item.default_vat_code,
194 supplier_ref: item.supplier_ref
195 }
196 }));
197 } else {
198 console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array.");
199 }
200 }, "json");
201 },
202 dataType: "json",
203 minLength: '.((int) $minLength).',
204 focus: function( event, ui ) {
205 if (ui.item.noresult) { return false; }
206 },
207 select: function( event, ui ) { // Function ran once a new value has been selected into the javascript combo
208 if (ui.item.noresult) { return false; }
209 console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'");
210 console.log("Selected id = "+ui.item.id+" - If this value is null, it means you select a record with key that is null so selection is not effective");
211
212 console.log("Before, we propagate some properties, retrieved by the ajax of the get, into the data-xxx properties of the component #'.$htmlnamejquery.'");
213 //console.log(ui.item);
214
215 // For supplier price and customer when price by quantity is off
216 $("#'.$htmlnamejquery.'").attr("data-up", ui.item.price_ht);
217 $("#'.$htmlnamejquery.'").attr("data-up-locale", ui.item.price_unit_ht_locale);
218 $("#'.$htmlnamejquery.'").attr("data-base", ui.item.pricebasetype);
219 $("#'.$htmlnamejquery.'").attr("data-qty", ui.item.qty);
220 $("#'.$htmlnamejquery.'").attr("data-discount", ui.item.discount);
221 $("#'.$htmlnamejquery.'").attr("data-description", ui.item.description);
222 $("#'.$htmlnamejquery.'").attr("data-ref-customer", ui.item.ref_customer);
223 $("#'.$htmlnamejquery.'").attr("data-tvatx", ui.item.tva_tx);
224 $("#'.$htmlnamejquery.'").attr("data-default-vat-code", ui.item.default_vat_code);
225 $("#'.$htmlnamejquery.'").attr("data-supplier-ref", ui.item.supplier_ref); // supplier_ref of price
226
227 // For multi-currency values
228 $("#'.$htmlnamejquery.'").attr("data-multicurrency-code", ui.item.multicurrency_code);
229 $("#'.$htmlnamejquery.'").attr("data-multicurrency-unitprice", ui.item.multicurrency_unitprice);
230 ';
231 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
232 $script .= '
233 // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on
234 console.log("PRODUIT_CUSTOMER_PRICES_BY_QTY is on, so we propagate also prices by quantity into data-pbqxxx properties");
235 $("#'.$htmlnamejquery.'").attr("data-pbq", ui.item.pbq);
236 $("#'.$htmlnamejquery.'").attr("data-pbqup", ui.item.price_ht);
237 $("#'.$htmlnamejquery.'").attr("data-pbqbase", ui.item.pricebasetype);
238 $("#'.$htmlnamejquery.'").attr("data-pbqqty", ui.item.qty);
239 $("#'.$htmlnamejquery.'").attr("data-pbqpercent", ui.item.discount);
240 ';
241 }
242 $script .= '
243 // A new value has been selected, we trigger the handlers on #htmlnamejquery
244 console.log("Now, we trigger changes on #'.$htmlnamejquery.'");
245 $("#'.$htmlnamejquery.'").val(ui.item.id).trigger("change"); // Select new value
246
247 // Complementary actions
248
249 // Disable an element
250 if (options.option_disabled) {
251 console.log("Make action option_disabled on #"+options.option_disabled+" with disabled="+ui.item.disabled)
252 if (ui.item.disabled) {
253 $("#" + options.option_disabled).prop("disabled", true);
254 if (options.error) {
255 $.jnotify(options.error, "error", true); // Output with jnotify the error message
256 }
257 if (options.warning) {
258 $.jnotify(options.warning, "warning", false); // Output with jnotify the warning message
259 }
260 } else {
261 $("#" + options.option_disabled).removeAttr("disabled");
262 }
263 }
264
265 if (options.disabled) {
266 console.log("Make action \'disabled\' on each "+options.option_disabled)
267 $.each(options.disabled, function(key, value) {
268 $("#" + value).prop("disabled", true);
269 });
270 }
271 if (options.show) {
272 console.log("Make action \'show\' on each "+options.show)
273 $.each(options.show, function(key, value) {
274 $("#" + value).show().trigger("show");
275 });
276 }
277
278 // Update an input
279 if (ui.item.update) {
280 console.log("Make action \'update\' on each ui.item.update (if there is)")
281 // loop on each "update" fields
282 $.each(ui.item.update, function(key, value) {
283 console.log("Set value "+value+" into #"+key);
284 $("#" + key).val(value).trigger("change");
285 });
286 }
287 if (ui.item.textarea) {
288 console.log("Make action \'textarea\' on each ui.item.textarea (if there is)")
289 $.each(ui.item.textarea, function(key, value) {
290 if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
291 CKEDITOR.instances[key].setData(value);
292 CKEDITOR.instances[key].focus();
293 } else {
294 $("#" + key).html(value);
295 $("#" + key).focus();
296 }
297 });
298 }
299 console.log("ajax_autocompleter new value selected, we trigger change also on original component so on field #search_'.$htmlname.'");
300
301 $("#search_'.$htmlnamejquery.'").trigger("change"); // We have changed value of the combo select, we must be sure to trigger all js hook binded on this event. This is required to trigger other javascript change method binded on original field by other code.
302 }
303 ,delay: 500
304 });
305 const widgetData = $("input#search_'.$htmlnamejquery.'").data("'.$dataforrenderITem.'");
306 if (widgetData) {
307 widgetData._renderItem = function( ul, item ) {
308 return $("<li>")
309 .addClass(item.noresult ? "ui-state-disabled" : "")
310 .data( "'.$dataforitem.'", item ) // jQuery UI > 1.10.0
311 .append( \'<a><span class="tag">\' + item.label + "</span></a>" )
312 .appendTo(ul);
313 };
314 }
315
316 });';
317 $script .= '</script>';
318
319 return $script;
320}
321
336function ajax_multiautocompleter($htmlname, $fields, $url, $option = '', $minLength = 2, $autoselect = 0)
337{
338 $script = '<!-- Autocomplete -->'."\n";
339 $script .= '<script>';
340 $script .= 'jQuery(document).ready(function() {
341 var fields = '.json_encode($fields).';
342 var nboffields = fields.length;
343 var autoselect = '.$autoselect.';
344 //alert(fields + " " + nboffields);
345
346 // Activate the autocomplete to execute the GET
347 jQuery("input#'.$htmlname.'").autocomplete({
348 dataType: "json",
349 minLength: '.$minLength.',
350 source: function( request, response ) {
351 jQuery.getJSON( "'.$url.($option ? '?'.$option : '').'", { '.$htmlname.': request.term }, function(data){
352 response( jQuery.map( data, function( item ) {
353 if (autoselect == 1 && data.length == 1) {
354 jQuery("#'.$htmlname.'").val(item.value);
355 // TODO move this to specific request
356 if (item.states) {
357 jQuery("#state_id").html(item.states);
358 }
359 for (i=0;i<nboffields;i++) {
360 if (item[fields[i]]) { // If defined
361 //alert(item[fields[i]]);
362 jQuery("#" + fields[i]).val(item[fields[i]]);
363 }
364 }
365 }
366 return item
367 }));
368 });
369 },
370 select: function( event, ui ) {
371 needtotrigger = "";
372 for (i=0;i<nboffields;i++) {
373 //alert(fields[i] + " = " + ui.item[fields[i]]);
374 if (fields[i]=="selectcountry_id")
375 {
376 if (ui.item[fields[i]] > 0) // Do not erase country if unknown
377 {
378 oldvalue=jQuery("#" + fields[i]).val();
379 newvalue=ui.item[fields[i]];
380 //alert(oldvalue+" "+newvalue);
381 jQuery("#" + fields[i]).val(ui.item[fields[i]]);
382 if (oldvalue != newvalue) // To force select2 to refresh visible content
383 {
384 needtotrigger="#" + fields[i];
385 }
386
387 // If we set new country and new state, we need to set a new list of state to allow change
388 if (ui.item.states && ui.item["state_id"] != jQuery("#state_id").value) {
389 jQuery("#state_id").html(ui.item.states);
390 }
391 }
392 }
393 else if (fields[i]=="state_id" || fields[i]=="state_id")
394 {
395 if (ui.item[fields[i]] > 0) // Do not erase state if unknown
396 {
397 oldvalue=jQuery("#" + fields[i]).val();
398 newvalue=ui.item[fields[i]];
399 //alert(oldvalue+" "+newvalue);
400 jQuery("#" + fields[i]).val(ui.item[fields[i]]); // This may fails if not correct country
401 if (oldvalue != newvalue) // To force select2 to refresh visible content
402 {
403 needtotrigger="#" + fields[i];
404 }
405 }
406 }
407 else if (ui.item[fields[i]]) { // If defined
408 oldvalue=jQuery("#" + fields[i]).val();
409 newvalue=ui.item[fields[i]];
410 //alert(oldvalue+" "+newvalue);
411 jQuery("#" + fields[i]).val(ui.item[fields[i]]);
412 if (oldvalue != newvalue) // To force select2 to refresh visible content
413 {
414 needtotrigger="#" + fields[i];
415 }
416 }
417
418 if (needtotrigger != "") // To force select2 to refresh visible content
419 {
420 // We introduce a delay so hand is back to js and all other js change can be done before the trigger that may execute a submit is done
421 // This is required for example when changing zip with autocomplete that change the country
422 jQuery(needtotrigger).delay(500).queue(function() {
423 jQuery(this).trigger("change");
424 });
425 }
426 }
427 }
428 });
429 });';
430 $script .= '</script>';
431
432 return $script;
433}
434
444function ajax_dialog($title, $message, $w = 350, $h = 150)
445{
446 $newtitle = dol_textishtml($title) ? dol_string_nohtmltag($title, 1) : $title;
447 $msg = '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
448 $msg .= $message;
449 $msg .= '</div>'."\n";
450 $msg .= '<script>
451 jQuery(function() {
452 jQuery("#dialog-info").dialog({
453 resizable: false,
454 height:'.$h.',
455 width:'.$w.',
456 modal: true,
457 buttons: {
458 Ok: function() {
459 jQuery(this).dialog(\'close\');
460 }
461 }
462 });
463 });
464 </script>';
465
466 $msg .= "\n";
467
468 return $msg;
469}
470
471
488function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = 0, $forcefocus = 0, $widthTypeOfAutocomplete = 'resolve', $idforemptyvalue = '-1', $morecss = '', $placeholder = '')
489{
490 global $conf;
491
492 // select2 can be disabled for smartphones
493 if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && getDolGlobalString('MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE')) {
494 return '';
495 }
496
497 if (getDolGlobalString('MAIN_DISABLE_AJAX_COMBOX')) {
498 return '';
499 }
500 if (empty($conf->use_javascript_ajax)) {
501 return '';
502 }
503 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
504 return '';
505 }
506 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
507 return '';
508 }
509
510 if (empty($minLengthToAutocomplete)) {
511 $minLengthToAutocomplete = 0;
512 }
513
514 $moreselect2theme = ($morecss ? dol_escape_js(' '.$morecss) : '');
515 $moreselect2theme = preg_replace('/widthcentpercentminus[^\s]*/', '', $moreselect2theme);
516
517 $tmpplugin = 'select2';
518 $componentname = (preg_match('/^\./', $htmlname) ? $htmlname : '#'.$htmlname); // To support when htmlname is not an ID but a class
519 $msg = "\n";
520 $msg .= '<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->'."\n";
521 $msg .= "<script>\n";
522 $msg .= '$(document).ready(function () {
523 $(\''.dol_escape_js($componentname).'\').'.$tmpplugin.'({';
524 // when $morecss contains 'onrightofpage', the select2 component must also be inside a parent with class="parentonrightofpage"
525 if (preg_match('/onrightofpage/', $morecss)) { // In this case, htmlname must be an ID not a class.
526 $msg .= ' dropdownAutoWidth: true, ';
527 $msg .= ' dropdownParent: $(\'#'.$htmlname.'\').parent(), ';
528 }
529 if ($placeholder) {
530 $msg .= '
531 placeholder: {
532 id: \'-1\',
533 text: \''.dol_escape_js($placeholder).'\'
534 },';
535 }
536 $msg .= '
537 dir: \'ltr\',
538 width: \''.dol_escape_js($widthTypeOfAutocomplete).'\', /* off or resolve */
539 minimumInputLength: '.((int) $minLengthToAutocomplete).',
540 language: (typeof select2arrayoflanguage === \'undefined\') ? \'en\' : select2arrayoflanguage,
541 matcher: function (params, data) {
542 if ($.trim(params.term) === "") { return data; }';
543 if (getDolGlobalString('MAIN_ENABLE_ACCENT_INSENSITIVE_SEARCH')) { // lowercase + remove accents
544 $msg .= '
545 var term = params.term.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase()
546 var searchText = data.element ? $(data.element).attr("data-search") : undefined;
547 var text = (searchText !== undefined ? searchText : (data.text || "")).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase() || "";';
548 } else { // lowercase only (accent kept)
549 $msg .= '
550 var term = params.term.toLowerCase();
551 var searchText = data.element ? $(data.element).attr("data-search") : undefined;
552 var text = (searchText !== undefined ? searchText : (data.text || "")).toLowerCase();';
553 }
554 $msg .= '
555 var keywords = term.split(" ");
556 for (var i = 0; i < keywords.length; i++) {
557 if (text.indexOf(keywords[i]) === -1) {
558 return null;
559 }
560 }
561 return data;
562 },
563 theme: \'default'.dol_escape_js($moreselect2theme).'\', /* to add css on generated html components */
564 containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
565 selectionCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
566 dropdownCssClass: \'dol-dropdown-dialog dol-dropdown-dialogmono\',
567 templateResult: function (data, container) { /* Format visible output into combo list */
568 /* Code to add class of origin OPTION propagated to the new select2 <li> tag */
569 if (data.element) { $(container).addClass($(data.element).attr("class")); }
570 /* console.log("data html is "+$(data.element).attr("data-html")); */
571 if (data.id == \''.(dol_escape_js($idforemptyvalue)).'\' && $(data.element).attr("data-html") == undefined) {
572 return \'&nbsp;\';
573 }
574 if ($(data.element).attr("data-html") != undefined) {
575 /* If property html set, we decode html entities and use this. */
576 /* Note that HTML content must have been sanitized against js injection with dol_escape_htmltag(xxx, 0, 0, \'\', 0, 1) when building the select option. */
577 if (typeof htmlEntityDecodeJs === "function") {
578 return htmlEntityDecodeJs($(data.element).attr("data-html"));
579 }
580 }
581 return data.text;
582 },
583 templateSelection: function (selection) { /* Format visible output of selected value */
584 if (selection.id == \''.(dol_escape_js($idforemptyvalue)).'\') return \'<span class="placeholder">\'+selection.text+\'</span>\';
585 if (selection.element && $(selection.element).attr("data-select-html") != undefined) {
586 if (typeof htmlEntityDecodeJs === "function") {
587 return htmlEntityDecodeJs($(selection.element).attr("data-select-html"));
588 }
589 }
590 return selection.text;
591 },
592 escapeMarkup: function(markup) {
593 return markup;
594 }
595 })';
596 if ($forcefocus) {
597 $msg .= '.select2(\'focus\')';
598 }
599 $msg .= ';'."\n";
600
601 $msg .= '});'."\n";
602 $msg .= "</script>\n";
603
604 $msg .= ajax_event($htmlname, $events);
605
606 return $msg;
607}
608
609
618function ajax_event($htmlname, $events)
619{
620 $out = '';
621
622 if (is_array($events) && count($events)) { // If an array of js events to do were provided.
623 $out = '<!-- JS code to manage event for id = ' . $htmlname . ' -->
624 <script>
625 $(document).ready(function () {
626 jQuery("#'.$htmlname.'").change(function () {
627 var obj = '.json_encode($events) . ';
628 $.each(obj, function(key,values) {
629 if (values.method.length) {
630 runJsCodeForEvent'.$htmlname.'(values);
631 }
632 });
633 });
634 function runJsCodeForEvent'.$htmlname.'(obj) {
635 var id = $("#'.$htmlname.'").val();
636 var method = obj.method;
637 var url = obj.url;
638 var htmlname = obj.htmlname;
639 var showempty = obj.showempty;
640 console.log("Run runJsCodeForEvent-'.$htmlname.' from ajax_combobox id="+id+" method="+method+" showempty="+showempty+" url="+url+" htmlname="+htmlname);
641 // The token is required because the request carries an "action" parameter: with
642 // MAIN_SECURITY_CSRF_WITH_TOKEN >= 3 (the default), such a GET is refused without it.
643 // currentToken() is used and not newToken() because the called pages set NOTOKENRENEWAL.
644 $.getJSON(url,
645 {
646 action: method,
647 id: id,
648 htmlname: htmlname,
649 showempty: showempty,
650 token: \''.currentToken().'\'
651 },
652 function(response) {
653 $.each(obj.params, function(key,action) {
654 if (key.length) {
655 var num = response.num;
656 if (num > 0) {
657 $("#" + key).removeAttr(action);
658 } else {
659 $("#" + key).attr(action, action);
660 }
661 }
662 });
663
664 console.log("Replace HTML content of select#"+htmlname);
665 $("select#" + htmlname).html(response.value);
666 if (response.num) {
667 var selecthtml_str = response.value; /* response.value is the HTML string with list of options */
668 var selecthtml_dom=$.parseHTML(selecthtml_str);
669 if (typeof(selecthtml_dom[0][0]) !== \'undefined\') {
670 $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML);
671 }
672 } else {
673 $("#inputautocomplete"+htmlname).val("");
674 }
675 $("select#" + htmlname).change(); /* Trigger event change */
676 }
677 );
678 }
679 });
680 </script>';
681 }
682
683 return $out;
684}
685
686
708function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0, $setzeroinsteadofdel = 0, $suffix = '', $mode = '', $morecss = 'inline-block', $userconst = 0, $showwarning = '', $disabled = 0)
709{
710 global $conf, $langs, $user, $db;
711
712 $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity);
713 if (!isset($input)) {
714 $input = array();
715 }
716
717 $out = '';
718
719 if (empty($conf->use_javascript_ajax) || $forcenoajax) {
720 if (!getDolGlobalString($code)) {
721 $out = '<a '.($morecss ? 'class="'.$morecss.'" ' : '').'href="'.$_SERVER['PHP_SELF'].'?action=set_'.$code.'&token='.newToken().'&entity='.$entity.($mode ? '&mode='.$mode : '').($forcereload ? '&dol_resetcache=1' : '').'">'.img_picto($langs->trans("Disabled"), 'off').'</a>';
722 } else {
723 $out = '<a '.($morecss ? 'class="'.$morecss.'" ' : '').' href="'.$_SERVER['PHP_SELF'].'?action=del_'.$code.'&token='.newToken().'&entity='.$entity.($mode ? '&mode='.$mode : '').($forcereload ? '&dol_resetcache=1' : '').'">'.img_picto($langs->trans("Enabled"), 'on').'</a>';
724 }
725 } else {
726 $userconstid = 0;
727 if (is_object($userconst)) {
728 $userconstid = $userconst->id;
729 } elseif (is_numeric($userconst) && $userconst > 0) {
730 $userconstid = $userconst;
731 $userconst = new User($db);
732 $userconst->fetch($userconstid);
733 }
734
735 if ($disabled) {
736 $morecss .= ' disabled opacitymedium';
737 } else {
738 $out = "\n<!-- Ajax code to switch constant ".$code." -->".'
739 <script>
740 $(document).ready(function() {
741 var input = '.json_encode($input).';
742 var url = \''.DOL_URL_ROOT.'/core/ajax/constantonoff.php\';
743 var code = \''.dol_escape_js($code).'\';
744 var entity = \''.dol_escape_js((string) $entity).'\';
745 var strict = \''.dol_escape_js((string) $strict).'\';
746 var userid = \''.dol_escape_js((string) $user->id).'\';
747 var userconst = '.((int) $userconstid).';
748 var yesButton = \''.dol_escape_js($langs->transnoentities("Yes")).'\';
749 var noButton = \''.dol_escape_js($langs->transnoentities("No")).'\';
750 var token = \''.currentToken().'\';
751 var warning = \''.dol_escape_js($showwarning).'\';
752
753 // Set constant
754 $("#set_" + code).click(function() {
755 if (warning) {
756 alert(warning);
757 }
758
759 if (input.alert && input.alert.set) {
760 if (input.alert.set.yesButton) yesButton = input.alert.set.yesButton;
761 if (input.alert.set.noButton) noButton = input.alert.set.noButton;
762 confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid, token);
763 } else {
764 setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 1, userconst);
765 }
766 });
767
768 // Del constant
769 $("#del_" + code).click(function() {
770 if (input.alert && input.alert.del) {
771 if (input.alert.del.yesButton) yesButton = input.alert.del.yesButton;
772 if (input.alert.del.noButton) noButton = input.alert.del.noButton;
773 confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid, token);
774 } else {';
775 if (empty($setzeroinsteadofdel)) {
776 $out .= ' delConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, userconst);';
777 } else {
778 $out .= ' setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 0, userconst);';
779 }
780 $out .= ' }
781 });
782 });
783 </script>'."\n";
784 }
785
786 if (!empty($userconst) && $userconst instanceof User) {
787 $value = getDolUserString($code, '', $userconst);
788 } else {
789 $value = getDolGlobalString($code);
790 }
791
792 if (is_array($suffix)) {
793 $suffixon = $suffix['ifon'];
794 $suffixoff = $suffix['ifoff'];
795 } else { // old mode deprecated
796 $suffixon = (string) $suffix;
797 $suffixoff = '';
798 }
799
800 $out .= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
801 $out .= '<span id="set_'.$code.'" class="valignmiddle inline-block linkobject '.($value ? 'hideobject' : '').($morecss ? ' '.$morecss : '').'">'.($revertonoff ? img_picto($langs->trans("Enabled"), 'switch_on'.$suffixoff, '', 0, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Disabled"), 'switch_off'.$suffixoff, '', 0, 0, 0, '', '', $marginleftonlyshort)).'</span>';
802 $out .= '<span id="del_'.$code.'" class="valignmiddle inline-block linkobject '.($value ? '' : 'hideobject').($morecss ? ' '.$morecss : '').'">'.($revertonoff ? img_picto($langs->trans("Disabled"), 'switch_off'.$suffixon, '', 0, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Enabled"), 'switch_on'.$suffixon, '', 0, 0, 0, '', '', $marginleftonlyshort)).'</span>';
803 $out .= "\n";
804 }
805
806 return $out;
807}
808
827function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array(), $morecss = '', $htmlname = '', $forcenojs = 0, $moreparam = '', $readonly = 0)
828{
829 global $conf, $langs;
830
831 if (empty($htmlname)) {
832 $htmlname = $code;
833 }
834
835 $out = '';
836
837 if (!empty($conf->use_javascript_ajax) && empty($forcenojs) && empty($readonly)) {
838 $out .= '<script>
839 $(function() {
840 var input = '.json_encode($input).';
841
842 // Set constant
843 $("#set_'.$htmlname.'_'.$object->id.'").click(function() {
844 console.log("Click managed by ajax_object_onoff");
845 $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
846 action: \'set\',
847 field: \''.dol_escape_js($field).'\',
848 value: \'1\',
849 element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
850 id: \''.((int) $object->id).'\',
851 token: \''.currentToken().'\'
852 }).done(
853 function(response) {
854 try {
855 var data = JSON.parse(response);
856 console.log(data);
857 } catch (e) {
858 console.log(response);
859 }
860
861 $("#set_'.$htmlname.'_'.$object->id.'").hide();
862 $("#del_'.$htmlname.'_'.$object->id.'").show();
863 // Enable another element
864 if (input.disabled && input.disabled.length > 0) {
865 $.each(input.disabled, function(key,value) {
866 $("#" + value).removeAttr("disabled");
867 if ($("#" + value).hasClass("butActionRefused") == true) {
868 $("#" + value).removeClass("butActionRefused");
869 $("#" + value).addClass("butAction");
870 }
871 });
872 // Show another element
873 } else if (input.showhide && input.showhide.length > 0) {
874 $.each(input.showhide, function(key,value) {
875 $("#" + value).show();
876 });
877 }
878 }).fail(
879 function(response) {
880 //alert(response.responseText);
881 console.warn(response.responseText);
882 Dolibarr.tools.setEventMessage(response.responseText, "errors");
883 }
884 );
885 });
886
887 // Del constant
888 $("#del_'.$htmlname.'_'.$object->id.'").click(function() {
889 console.log("Click managed by ajax_object_onoff");
890 $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
891 action: \'set\',
892 field: \''.dol_escape_js($field).'\',
893 value: \'0\',
894 element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
895 id: \''.((int) $object->id).'\',
896 token: \''.currentToken().'\'
897 }).done(
898 function(response) {
899 try {
900 var data = JSON.parse(response);
901 console.log(data);
902 } catch (e) {
903 console.log(response);
904 }
905
906 $("#del_'.$htmlname.'_'.$object->id.'").hide();
907 $("#set_'.$htmlname.'_'.$object->id.'").show();
908 // Disable another element
909 if (input.disabled && input.disabled.length > 0) {
910 $.each(input.disabled, function(key,value) {
911 $("#" + value).prop("disabled", true);
912 if ($("#" + value).hasClass("butAction") == true) {
913 $("#" + value).removeClass("butAction");
914 $("#" + value).addClass("butActionRefused");
915 }
916 });
917 // Hide another element
918 } else if (input.showhide && input.showhide.length > 0) {
919 $.each(input.showhide, function(key,value) {
920 $("#" + value).hide();
921 });
922 }
923 }).fail(
924 function(response) {
925 //alert(response.responseText);
926 console.warn(response.responseText);
927 Dolibarr.tools.setEventMessage(response.responseText, "errors");
928 }
929 );
930 });
931 });
932 </script>';
933 }
934
935 $switchon = 'switch_on';
936 $switchoff = 'switch_off';
937 $cssswitchon = '';
938 $cssswitchoff = '';
939 $tmparray = explode(':', $text_on);
940 if (!empty($tmparray[1])) {
941 $text_on = $tmparray[0];
942 $switchon = $tmparray[1];
943 if (!empty($tmparray[2])) {
944 $cssswitchon = $tmparray[2];
945 }
946 }
947 $tmparray = explode(':', $text_off);
948 if (!empty($tmparray[1])) {
949 $text_off = $tmparray[0];
950 $switchoff = $tmparray[1];
951 if (!empty($tmparray[2])) {
952 $cssswitchoff = $tmparray[2];
953 }
954 }
955
956 if (empty($conf->use_javascript_ajax) || $forcenojs) {
957 $url = DOL_URL_ROOT.'/core/ajax/objectonoff.php?action=set&token='.newToken().'&id='.((int) $object->id).'&element='.urlencode($object->element).'&field='.urlencode($field).'&value=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.($moreparam ? '&'.$moreparam : ''));
958 if ($readonly) {
959 $url = '#';
960 }
961 $out .= '<a id="set_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? 'hideobject' : '').($morecss ? ' '.$morecss : '').'" href="'.$url.'">'.img_picto($langs->trans($text_off), $switchoff, '', 0, 0, 0, '', $cssswitchoff).'</a>';
962 $url = DOL_URL_ROOT.'/core/ajax/objectonoff.php?action=set&token='.newToken().'&id='.((int) $object->id).'&element='.urlencode($object->element).'&field='.urlencode($field).'&value=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.($moreparam ? '&'.$moreparam : ''));
963 if ($readonly) {
964 $url = '#';
965 }
966 $out .= '<a id="del_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? '' : 'hideobject').($morecss ? ' '.$morecss : '').'" href="'.$url.'">'.img_picto($langs->trans($text_on), $switchon, '', 0, 0, 0, '', $cssswitchon).'</a>';
967 } else {
968 $out .= '<span id="set_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? 'hideobject' : '').($morecss ? ' '.$morecss : '').'">'.img_picto($langs->trans($text_off), $switchoff, '', 0, 0, 0, '', $cssswitchoff).'</span>';
969 $out .= '<span id="del_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? '' : 'hideobject').($morecss ? ' '.$morecss : '').'">'.img_picto($langs->trans($text_on), $switchon, '', 0, 0, 0, '', $cssswitchon).'</span>';
970 }
971
972 return $out;
973}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array(), $moreparams='')
Generic function that return javascript to add to transform a common input text or select field into ...
Definition ajax.lib.php:51
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
ajax_dialog($title, $message, $w=350, $h=150)
Show an ajax dialog.
Definition ajax.lib.php:444
ajax_multiautocompleter($htmlname, $fields, $url, $option='', $minLength=2, $autoselect=0)
Generic function that return javascript to add to a page to transform a common input text field into ...
Definition ajax.lib.php:336
ajax_event($htmlname, $events)
Add event management script.
Definition ajax.lib.php:618
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage Dolibarr users.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
currentToken()
Return the value of token currently saved into session with name 'token'.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
if(empty( $takeposterminal)) fail($message)
Abort invoice creation with a given error message.
Definition invoice.php:125