dolibarr 18.0.6
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 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
47function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array(), $moreparams = '')
48{
49 global $conf;
50
51 if (empty($minLength)) {
52 $minLength = 1;
53 }
54
55 $dataforrenderITem = 'ui-autocomplete';
56 $dataforitem = 'ui-autocomplete-item';
57 // Allow two constant to use other values for backward compatibility
58 if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) {
59 $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
60 }
61 if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) {
62 $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM');
63 }
64
65 $htmlnamejquery = str_replace('.', '\\\\.', $htmlname);
66
67 // Input search_htmlname is original field
68 // Input htmlname is a second input field used when using ajax autocomplete.
69 $script = '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" '.($moreparams ? $moreparams : '').' />';
70
71 $script .= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
72 $script .= '<script>'."\n";
73 $script .= '$(document).ready(function() {
74 var autoselect = '.((int) $autoselect).';
75 var options = '.json_encode($ajaxoptions).'; /* Option of actions to do after keyup, or after select */
76
77 /* 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 loosing the product id. This is needed only for select of predefined product */
78 $("input#search_'.$htmlnamejquery.'").keydown(function(e) {
79 if (e.keyCode != 9) /* If not "Tab" key */
80 {
81 if (e.keyCode == 13) { return false; } /* disable "ENTER" key useful for barcode readers */
82 console.log("Clear id previously selected for field '.$htmlname.'");
83 $("#'.$htmlnamejquery.'").val("");
84 }
85 });
86
87 // Check options for secondary actions when keyup
88 $("input#search_'.$htmlnamejquery.'").keyup(function() {
89 if ($(this).val().length == 0)
90 {
91 $("#search_'.$htmlnamejquery.'").val("");
92 $("#'.$htmlnamejquery.'").val("").trigger("change");
93 if (options.option_disabled) {
94 $("#" + options.option_disabled).removeAttr("disabled");
95 }
96 if (options.disabled) {
97 $.each(options.disabled, function(key, value) {
98 $("#" + value).removeAttr("disabled");
99 });
100 }
101 if (options.update) {
102 $.each(options.update, function(key, value) {
103 $("#" + key).val("").trigger("change");
104 });
105 }
106 if (options.show) {
107 $.each(options.show, function(key, value) {
108 $("#" + value).hide().trigger("hide");
109 });
110 }
111 if (options.update_textarea) {
112 $.each(options.update_textarea, function(key, value) {
113 if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
114 CKEDITOR.instances[key].setData("");
115 } else {
116 $("#" + key).html("");
117 }
118 });
119 }
120 }
121 });
122
123 $("input#search_'.$htmlnamejquery.'").autocomplete({
124 source: function( request, response ) {
125 $.get("'.$url.($urloption ? '?'.$urloption : '').'", { "'.str_replace('.', '_', $htmlname).'": request.term }, function(data){
126 if (data != null)
127 {
128 response($.map( data, function(item) {
129 if (autoselect == 1 && data.length == 1) {
130 $("#search_'.$htmlnamejquery.'").val(item.value);
131 $("#'.$htmlnamejquery.'").val(item.key).trigger("change");
132 }
133 var label = "";
134 if (item.label != null) {
135 label = item.label.toString();
136 }
137 var update = {};
138 if (options.update) {
139 $.each(options.update, function(key, value) {
140 update[key] = item[value];
141 });
142 }
143 var textarea = {};
144 if (options.update_textarea) {
145 $.each(options.update_textarea, function(key, value) {
146 textarea[key] = item[value];
147 });
148 }
149
150 console.log("Return value from GET to the rest of code");
151 return { label: label,
152 value: item.value,
153 id: item.key,
154 disabled: item.disabled,
155 update: update,
156 textarea: textarea,
157 pbq: item.pbq,
158 type: item.type,
159 qty: item.qty,
160 discount: item.discount,
161 pricebasetype: item.pricebasetype,
162 price_ht: item.price_ht,
163 price_ttc: item.price_ttc,
164 price_unit_ht: item.price_unit_ht,
165 price_unit_ht_locale: item.price_unit_ht_locale,
166 ';
167 if (isModEnabled('multicurrency')) {
168 $script .= '
169 multicurrency_code: item.multicurrency_code,
170 multicurrency_unitprice: item.multicurrency_unitprice,
171 ';
172 }
173 $script .= '
174 description : item.description,
175 ref_customer: item.ref_customer,
176 tva_tx: item.tva_tx,
177 default_vat_code: item.default_vat_code
178 }
179 }));
180 } else {
181 console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array.");
182 }
183 }, "json");
184 },
185 dataType: "json",
186 minLength: '.((int) $minLength).',
187 select: function( event, ui ) { // Function ran once new value has been selected into javascript combo
188 console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'");
189 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");
190
191 console.log("Propagate before some properties retrieved by ajax into data-xxx properties of #'.$htmlnamejquery.' component");
192 //console.log(ui.item);
193
194 // For supplier price and customer when price by quantity is off
195 $("#'.$htmlnamejquery.'").attr("data-up", ui.item.price_ht);
196 $("#'.$htmlnamejquery.'").attr("data-up-locale", ui.item.price_unit_ht_locale);
197 $("#'.$htmlnamejquery.'").attr("data-base", ui.item.pricebasetype);
198 $("#'.$htmlnamejquery.'").attr("data-qty", ui.item.qty);
199 $("#'.$htmlnamejquery.'").attr("data-discount", ui.item.discount);
200 $("#'.$htmlnamejquery.'").attr("data-description", ui.item.description);
201 $("#'.$htmlnamejquery.'").attr("data-ref-customer", ui.item.ref_customer);
202 $("#'.$htmlnamejquery.'").attr("data-tvatx", ui.item.tva_tx);
203 $("#'.$htmlnamejquery.'").attr("data-default-vat-code", ui.item.default_vat_code);
204 ';
205 if (isModEnabled('multicurrency')) {
206 $script .= '
207 // For multi-currency values
208 $("#'.$htmlnamejquery.'").attr("data-multicurrency-code", ui.item.multicurrency_code);
209 $("#'.$htmlnamejquery.'").attr("data-multicurrency-unitprice", ui.item.multicurrency_unitprice);
210 ';
211 }
212 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
213 $script .= '
214 // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on
215 console.log("PRODUIT_CUSTOMER_PRICES_BY_QTY is on, propagate also prices by quantity into data-pbqxxx properties");
216 $("#'.$htmlnamejquery.'").attr("data-pbq", ui.item.pbq);
217 $("#'.$htmlnamejquery.'").attr("data-pbqup", ui.item.price_ht);
218 $("#'.$htmlnamejquery.'").attr("data-pbqbase", ui.item.pricebasetype);
219 $("#'.$htmlnamejquery.'").attr("data-pbqqty", ui.item.qty);
220 $("#'.$htmlnamejquery.'").attr("data-pbqpercent", ui.item.discount);
221 ';
222 }
223 $script .= '
224 // A new value has been selected, we trigger the handlers on #htmlnamejquery
225 console.log("Trigger changes on #'.$htmlnamejquery.'");
226 $("#'.$htmlnamejquery.'").val(ui.item.id).trigger("change"); // Select new value
227
228 // Complementary actions
229
230 // Disable an element
231 if (options.option_disabled) {
232 console.log("Make action option_disabled on #"+options.option_disabled+" with disabled="+ui.item.disabled)
233 if (ui.item.disabled) {
234 $("#" + options.option_disabled).prop("disabled", true);
235 if (options.error) {
236 $.jnotify(options.error, "error", true); // Output with jnotify the error message
237 }
238 if (options.warning) {
239 $.jnotify(options.warning, "warning", false); // Output with jnotify the warning message
240 }
241 } else {
242 $("#" + options.option_disabled).removeAttr("disabled");
243 }
244 }
245
246 if (options.disabled) {
247 console.log("Make action disabled on each "+options.option_disabled)
248 $.each(options.disabled, function(key, value) {
249 $("#" + value).prop("disabled", true);
250 });
251 }
252 if (options.show) {
253 console.log("Make action show on each "+options.show)
254 $.each(options.show, function(key, value) {
255 $("#" + value).show().trigger("show");
256 });
257 }
258
259 // Update an input
260 if (ui.item.update) {
261 console.log("Make action update on each ui.item.update (if there is)")
262 // loop on each "update" fields
263 $.each(ui.item.update, function(key, value) {
264 console.log("Set value "+value+" into #"+key);
265 $("#" + key).val(value).trigger("change");
266 });
267 }
268 if (ui.item.textarea) {
269 console.log("Make action textarea on each ui.item.textarea (if there is)")
270 $.each(ui.item.textarea, function(key, value) {
271 if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
272 CKEDITOR.instances[key].setData(value);
273 CKEDITOR.instances[key].focus();
274 } else {
275 $("#" + key).html(value);
276 $("#" + key).focus();
277 }
278 });
279 }
280 console.log("ajax_autocompleter new value selected, we trigger change also on original component so on field #search_'.$htmlname.'");
281
282 $("#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.
283 }
284 ,delay: 500
285 }).data("'.$dataforrenderITem.'")._renderItem = function( ul, item ) {
286 return $("<li>")
287 .data( "'.$dataforitem.'", item ) // jQuery UI > 1.10.0
288 .append( \'<a><span class="tag">\' + item.label + "</span></a>" )
289 .appendTo(ul);
290 };
291
292 });';
293 $script .= '</script>';
294
295 return $script;
296}
297
312function ajax_multiautocompleter($htmlname, $fields, $url, $option = '', $minLength = 2, $autoselect = 0)
313{
314 $script = '<!-- Autocomplete -->'."\n";
315 $script .= '<script>';
316 $script .= 'jQuery(document).ready(function() {
317 var fields = '.json_encode($fields).';
318 var nboffields = fields.length;
319 var autoselect = '.$autoselect.';
320 //alert(fields + " " + nboffields);
321
322 jQuery("input#'.$htmlname.'").autocomplete({
323 dataType: "json",
324 minLength: '.$minLength.',
325 source: function( request, response ) {
326 jQuery.getJSON( "'.$url.($option ? '?'.$option : '').'", { '.$htmlname.': request.term }, function(data){
327 response( jQuery.map( data, function( item ) {
328 if (autoselect == 1 && data.length == 1) {
329 jQuery("#'.$htmlname.'").val(item.value);
330 // TODO move this to specific request
331 if (item.states) {
332 jQuery("#state_id").html(item.states);
333 }
334 for (i=0;i<nboffields;i++) {
335 if (item[fields[i]]) { // If defined
336 //alert(item[fields[i]]);
337 jQuery("#" + fields[i]).val(item[fields[i]]);
338 }
339 }
340 }
341 return item
342 }));
343 });
344 },
345 select: function( event, ui ) {
346 needtotrigger = "";
347 for (i=0;i<nboffields;i++) {
348 //alert(fields[i] + " = " + ui.item[fields[i]]);
349 if (fields[i]=="selectcountry_id")
350 {
351 if (ui.item[fields[i]] > 0) // Do not erase country if unknown
352 {
353 oldvalue=jQuery("#" + fields[i]).val();
354 newvalue=ui.item[fields[i]];
355 //alert(oldvalue+" "+newvalue);
356 jQuery("#" + fields[i]).val(ui.item[fields[i]]);
357 if (oldvalue != newvalue) // To force select2 to refresh visible content
358 {
359 needtotrigger="#" + fields[i];
360 }
361
362 // If we set new country and new state, we need to set a new list of state to allow change
363 if (ui.item.states && ui.item["state_id"] != jQuery("#state_id").value) {
364 jQuery("#state_id").html(ui.item.states);
365 }
366 }
367 }
368 else if (fields[i]=="state_id" || fields[i]=="state_id")
369 {
370 if (ui.item[fields[i]] > 0) // Do not erase state if unknown
371 {
372 oldvalue=jQuery("#" + fields[i]).val();
373 newvalue=ui.item[fields[i]];
374 //alert(oldvalue+" "+newvalue);
375 jQuery("#" + fields[i]).val(ui.item[fields[i]]); // This may fails if not correct country
376 if (oldvalue != newvalue) // To force select2 to refresh visible content
377 {
378 needtotrigger="#" + fields[i];
379 }
380 }
381 }
382 else if (ui.item[fields[i]]) { // If defined
383 oldvalue=jQuery("#" + fields[i]).val();
384 newvalue=ui.item[fields[i]];
385 //alert(oldvalue+" "+newvalue);
386 jQuery("#" + fields[i]).val(ui.item[fields[i]]);
387 if (oldvalue != newvalue) // To force select2 to refresh visible content
388 {
389 needtotrigger="#" + fields[i];
390 }
391 }
392
393 if (needtotrigger != "") // To force select2 to refresh visible content
394 {
395 // 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
396 // This is required for example when changing zip with autocomplete that change the country
397 jQuery(needtotrigger).delay(500).queue(function() {
398 jQuery(this).trigger("change");
399 });
400 }
401 }
402 }
403 });
404 });';
405 $script .= '</script>';
406
407 return $script;
408}
409
419function ajax_dialog($title, $message, $w = 350, $h = 150)
420{
421 global $langs;
422
423 $newtitle = dol_textishtml($title) ?dol_string_nohtmltag($title, 1) : $title;
424 $msg = '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
425 $msg .= $message;
426 $msg .= '</div>'."\n";
427 $msg .= '<script>
428 jQuery(function() {
429 jQuery("#dialog-info").dialog({
430 resizable: false,
431 height:'.$h.',
432 width:'.$w.',
433 modal: true,
434 buttons: {
435 Ok: function() {
436 jQuery(this).dialog(\'close\');
437 }
438 }
439 });
440 });
441 </script>';
442
443 $msg .= "\n";
444
445 return $msg;
446}
447
448
464function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = 0, $forcefocus = 0, $widthTypeOfAutocomplete = 'resolve', $idforemptyvalue = '-1', $morecss = '')
465{
466 global $conf;
467
468 // select2 can be disabled for smartphones
469 if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && !empty($conf->global->MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE)) {
470 return '';
471 }
472
473 if (!empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) {
474 return '';
475 }
476 if (empty($conf->use_javascript_ajax)) {
477 return '';
478 }
479 if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
480 return '';
481 }
482 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
483 return '';
484 }
485
486 if (empty($minLengthToAutocomplete)) {
487 $minLengthToAutocomplete = 0;
488 }
489
490 $moreselect2theme = ($morecss ? dol_escape_js(' '.$morecss) : '');
491 $moreselect2theme = preg_replace('/widthcentpercentminus[^\s]*/', '', $moreselect2theme);
492
493 $tmpplugin = 'select2';
494 $msg = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
495 <script>
496 $(document).ready(function () {
497 $(\''.(preg_match('/^\./', $htmlname) ? $htmlname : '#'.$htmlname).'\').'.$tmpplugin.'({
498 dir: \'ltr\',';
499 if (preg_match('/onrightofpage/', $morecss)) { // when $morecss contains 'onrightofpage', the select2 component must also be inside a parent with class="parentonrightofpage"
500 $msg .= ' dropdownAutoWidth: true, dropdownParent: $(\'#'.$htmlname.'\').parent(), '."\n";
501 }
502 $msg .= ' width: \''.dol_escape_js($widthTypeOfAutocomplete).'\', /* off or resolve */
503 minimumInputLength: '.((int) $minLengthToAutocomplete).',
504 language: select2arrayoflanguage,
505 matcher: function (params, data) {
506 if ($.trim(params.term) === "") {
507 return data;
508 }
509 keywords = (params.term).split(" ");
510 for (var i = 0; i < keywords.length; i++) {
511 if (((data.text).toUpperCase()).indexOf((keywords[i]).toUpperCase()) == -1) {
512 return null;
513 }
514 }
515 return data;
516 },
517 theme: \'default'.$moreselect2theme.'\', /* to add css on generated html components */
518 containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
519 selectionCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
520 dropdownCssClass: \'ui-dialog\',
521 templateResult: function (data, container) { /* Format visible output into combo list */
522 /* Code to add class of origin OPTION propagated to the new select2 <li> tag */
523 if (data.element) { $(container).addClass($(data.element).attr("class")); }
524 //console.log("data html is "+$(data.element).attr("data-html"));
525 if (data.id == '.((int) $idforemptyvalue).' && $(data.element).attr("data-html") == undefined) {
526 return \'&nbsp;\';
527 }
528 if ($(data.element).attr("data-html") != undefined) {
529 /* If property html set, we decode html entities and use this. */
530 /* Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, \'\', 0, 1) when building the select option. */
531 return htmlEntityDecodeJs($(data.element).attr("data-html"));
532 }
533 return data.text;
534 },
535 templateSelection: function (selection) { /* Format visible output of selected value */
536 if (selection.id == '.((int) $idforemptyvalue).') return \'<span class="placeholder">\'+selection.text+\'</span>\';
537 return selection.text;
538 },
539 escapeMarkup: function(markup) {
540 return markup;
541 }
542 })';
543 if ($forcefocus) {
544 $msg .= '.select2(\'focus\')';
545 }
546 $msg .= ';'."\n";
547
548 $msg .= '});'."\n";
549 $msg .= "</script>\n";
550
551 $msg .= ajax_event($htmlname, $events);
552
553 return $msg;
554}
555
556
565function ajax_event($htmlname, $events)
566{
567 $out = '';
568
569 if (is_array($events) && count($events)) { // If an array of js events to do were provided.
570 $out = '<!-- JS code to manage event for id = ' . $htmlname . ' -->
571 <script>
572 $(document).ready(function () {
573 jQuery("#'.$htmlname.'").change(function () {
574 var obj = '.json_encode($events) . ';
575 $.each(obj, function(key,values) {
576 if (values.method.length) {
577 runJsCodeForEvent'.$htmlname.'(values);
578 }
579 });
580 });
581 function runJsCodeForEvent'.$htmlname.'(obj) {
582 var id = $("#'.$htmlname.'").val();
583 var method = obj.method;
584 var url = obj.url;
585 var htmlname = obj.htmlname;
586 var showempty = obj.showempty;
587 console.log("Run runJsCodeForEvent-'.$htmlname.' from ajax_combobox id="+id+" method="+method+" showempty="+showempty+" url="+url+" htmlname="+htmlname);
588 $.getJSON(url,
589 {
590 action: method,
591 id: id,
592 htmlname: htmlname,
593 showempty: showempty
594 },
595 function(response) {
596 $.each(obj.params, function(key,action) {
597 if (key.length) {
598 var num = response.num;
599 if (num > 0) {
600 $("#" + key).removeAttr(action);
601 } else {
602 $("#" + key).attr(action, action);
603 }
604 }
605 });
606 $("select#" + htmlname).html(response.value);
607 if (response.num) {
608 var selecthtml_str = response.value;
609 var selecthtml_dom=$.parseHTML(selecthtml_str);
610 if (typeof(selecthtml_dom[0][0]) !== \'undefined\') {
611 $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML);
612 }
613 } else {
614 $("#inputautocomplete"+htmlname).val("");
615 }
616 $("select#" + htmlname).change(); /* Trigger event change */
617 }
618 );
619 }
620 });
621 </script>';
622 }
623
624 return $out;
625}
626
627
645function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0, $setzeroinsteadofdel = 0, $suffix = '', $mode = '', $morecss = '')
646{
647 global $conf, $langs, $user;
648
649 $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity);
650 if (!isset($input)) {
651 $input = array();
652 }
653
654 if (empty($conf->use_javascript_ajax) || $forcenoajax) {
655 if (empty($conf->global->$code)) {
656 print '<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>';
657 } else {
658 print '<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>';
659 }
660 } else {
661 $out = "\n<!-- Ajax code to switch constant ".$code." -->".'
662 <script>
663 $(document).ready(function() {
664 var input = '.json_encode($input).';
665 var url = \''.DOL_URL_ROOT.'/core/ajax/constantonoff.php\';
666 var code = \''.dol_escape_js($code).'\';
667 var entity = \''.dol_escape_js($entity).'\';
668 var strict = \''.dol_escape_js($strict).'\';
669 var userid = \''.dol_escape_js($user->id).'\';
670 var yesButton = \''.dol_escape_js($langs->transnoentities("Yes")).'\';
671 var noButton = \''.dol_escape_js($langs->transnoentities("No")).'\';
672 var token = \''.currentToken().'\';
673
674 // Set constant
675 $("#set_" + code).click(function() {
676 if (input.alert && input.alert.set) {
677 if (input.alert.set.yesButton) yesButton = input.alert.set.yesButton;
678 if (input.alert.set.noButton) noButton = input.alert.set.noButton;
679 confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid, token);
680 } else {
681 setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);
682 }
683 });
684
685 // Del constant
686 $("#del_" + code).click(function() {
687 if (input.alert && input.alert.del) {
688 if (input.alert.del.yesButton) yesButton = input.alert.del.yesButton;
689 if (input.alert.del.noButton) noButton = input.alert.del.noButton;
690 confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid, token);
691 } else {';
692 if (empty($setzeroinsteadofdel)) {
693 $out .=' delConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);';
694 } else {
695 $out .=' setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 0);';
696 }
697 $out .= ' }
698 });
699 });
700 </script>'."\n";
701
702 $out .= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
703 $out .= '<span id="set_'.$code.'" class="valignmiddle linkobject '.(!empty($conf->global->$code) ? 'hideobject' : '').'">'.($revertonoff ?img_picto($langs->trans("Enabled"), 'switch_on', '', false, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Disabled"), 'switch_off', '', false, 0, 0, '', '', $marginleftonlyshort)).'</span>';
704 $out .= '<span id="del_'.$code.'" class="valignmiddle linkobject '.(!empty($conf->global->$code) ? '' : 'hideobject').'">'.($revertonoff ?img_picto($langs->trans("Disabled"), 'switch_off'.$suffix, '', false, 0, 0, '', '', $marginleftonlyshort) : img_picto($langs->trans("Enabled"), 'switch_on'.$suffix, '', false, 0, 0, '', '', $marginleftonlyshort)).'</span>';
705 $out .= "\n";
706 }
707
708 return $out;
709}
710
726function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array(), $morecss = '', $htmlname = '', $forcenojs = 0)
727{
728 global $conf, $langs;
729
730 if (empty($htmlname)) {
731 $htmlname = $code;
732 }
733 //var_dump($object->module); var_dump($object->element);
734
735 $out = '';
736
737 if (!empty($conf->use_javascript_ajax)) {
738 $out .= '<script>
739 $(function() {
740 var input = '.json_encode($input).';
741
742 // Set constant
743 $("#set_'.$htmlname.'_'.$object->id.'").click(function() {
744 console.log("Click managed by ajax_object_onoff");
745 $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
746 action: \'set\',
747 field: \''.dol_escape_js($field).'\',
748 value: \'1\',
749 element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
750 id: \''.((int) $object->id).'\',
751 token: \''.currentToken().'\'
752 },
753 function() {
754 $("#set_'.$htmlname.'_'.$object->id.'").hide();
755 $("#del_'.$htmlname.'_'.$object->id.'").show();
756 // Enable another element
757 if (input.disabled && input.disabled.length > 0) {
758 $.each(input.disabled, function(key,value) {
759 $("#" + value).removeAttr("disabled");
760 if ($("#" + value).hasClass("butActionRefused") == true) {
761 $("#" + value).removeClass("butActionRefused");
762 $("#" + value).addClass("butAction");
763 }
764 });
765 // Show another element
766 } else if (input.showhide && input.showhide.length > 0) {
767 $.each(input.showhide, function(key,value) {
768 $("#" + value).show();
769 });
770 }
771 });
772 });
773
774 // Del constant
775 $("#del_'.$htmlname.'_'.$object->id.'").click(function() {
776 console.log("Click managed by ajax_object_onoff");
777 $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
778 action: \'set\',
779 field: \''.dol_escape_js($field).'\',
780 value: \'0\',
781 element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
782 id: \''.((int) $object->id).'\',
783 token: \''.currentToken().'\'
784 },
785 function() {
786 $("#del_'.$htmlname.'_'.$object->id.'").hide();
787 $("#set_'.$htmlname.'_'.$object->id.'").show();
788 // Disable another element
789 if (input.disabled && input.disabled.length > 0) {
790 $.each(input.disabled, function(key,value) {
791 $("#" + value).prop("disabled", true);
792 if ($("#" + value).hasClass("butAction") == true) {
793 $("#" + value).removeClass("butAction");
794 $("#" + value).addClass("butActionRefused");
795 }
796 });
797 // Hide another element
798 } else if (input.showhide && input.showhide.length > 0) {
799 $.each(input.showhide, function(key,value) {
800 $("#" + value).hide();
801 });
802 }
803 });
804 });
805 });
806 </script>';
807 }
808
809 $switchon = 'switch_on';
810 $switchoff = 'switch_off';
811 $cssswitchon = '';
812 $cssswitchoff = '';
813 $tmparray = explode(':', $text_on);
814 if (!empty($tmparray[1])) {
815 $text_on = $tmparray[0];
816 $switchon = $tmparray[1];
817 if (!empty($tmparray[2])) {
818 $cssswitchon = $tmparray[2];
819 }
820 }
821 $tmparray = explode(':', $text_off);
822 if (!empty($tmparray[1])) {
823 $text_off = $tmparray[0];
824 $switchoff = $tmparray[1];
825 if (!empty($tmparray[2])) {
826 $cssswitchoff = $tmparray[2];
827 }
828 }
829
830 if (empty($conf->use_javascript_ajax) || $forcenojs) {
831 $out .= '<a id="set_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? 'hideobject' : '').($morecss ? ' '.$morecss : '').'" href="'.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).'">'.img_picto($langs->trans($text_off), $switchoff, '', false, 0, 0, '', $cssswitchoff).'</a>';
832 $out .= '<a id="del_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? '' : 'hideobject').($morecss ? ' '.$morecss : '').'" href="'.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).'">'.img_picto($langs->trans($text_on), $switchon, '', false, 0, 0, '', $cssswitchon).'</a>';
833 } else {
834 $out .= '<span id="set_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? 'hideobject' : '').($morecss ? ' '.$morecss : '').'">'.img_picto($langs->trans($text_off), $switchoff, '', false, 0, 0, '', $cssswitchoff).'</span>';
835 $out .= '<span id="del_'.$htmlname.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? '' : 'hideobject').($morecss ? ' '.$morecss : '').'">'.img_picto($langs->trans($text_on), $switchon, '', false, 0, 0, '', $cssswitchon).'</span>';
836 }
837
838 return $out;
839}
ajax_autocompleter($selected, $htmlname, $url, $urloption='', $minLength=2, $autoselect=0, $ajaxoptions=array(), $moreparams='')
Generic function that return javascript to add to a page to transform a common input field into an au...
Definition ajax.lib.php:47
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:464
ajax_dialog($title, $message, $w=350, $h=150)
Show an ajax dialog.
Definition ajax.lib.php:419
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 field into an au...
Definition ajax.lib.php:312
ajax_event($htmlname, $events)
Add event management script.
Definition ajax.lib.php:565
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'.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.