dolibarr 19.0.3
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 if (empty($minLength)) {
50 $minLength = 1;
51 }
52
53 $dataforrenderITem = 'ui-autocomplete';
54 $dataforitem = 'ui-autocomplete-item';
55 // Allow two constant to use other values for backward compatibility
56 if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) {
57 $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
58 }
59 if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) {
60 $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM');
61 }
62
63 $htmlnamejquery = str_replace('.', '\\\\.', $htmlname);
64
65 // Input search_htmlname is original field
66 // Input htmlname is a second input field used when using ajax autocomplete.
67 $script = '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" '.($moreparams ? $moreparams : '').' />';
68
69 $script .= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
70 $script .= '<script>'."\n";
71 $script .= '$(document).ready(function() {
72 var autoselect = '.((int) $autoselect).';
73 var options = '.json_encode($ajaxoptions).'; /* Option of actions to do after keyup, or after select */
74
75 /* 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 */
76 $("input#search_'.$htmlnamejquery.'").keydown(function(e) {
77 if (e.keyCode != 9) /* If not "Tab" key */
78 {
79 if (e.keyCode == 13) { return false; } /* disable "ENTER" key useful for barcode readers */
80 console.log("Clear id previously selected for field '.$htmlname.'");
81 $("#'.$htmlnamejquery.'").val("");
82 }
83 });
84
85 // Check options for secondary actions when keyup
86 $("input#search_'.$htmlnamejquery.'").keyup(function() {
87 if ($(this).val().length == 0)
88 {
89 $("#search_'.$htmlnamejquery.'").val("");
90 $("#'.$htmlnamejquery.'").val("").trigger("change");
91 if (options.option_disabled) {
92 $("#" + options.option_disabled).removeAttr("disabled");
93 }
94 if (options.disabled) {
95 $.each(options.disabled, function(key, value) {
96 $("#" + value).removeAttr("disabled");
97 });
98 }
99 if (options.update) {
100 $.each(options.update, function(key, value) {
101 $("#" + key).val("").trigger("change");
102 });
103 }
104 if (options.show) {
105 $.each(options.show, function(key, value) {
106 $("#" + value).hide().trigger("hide");
107 });
108 }
109 if (options.update_textarea) {
110 $.each(options.update_textarea, function(key, value) {
111 if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
112 CKEDITOR.instances[key].setData("");
113 } else {
114 $("#" + key).html("");
115 }
116 });
117 }
118 }
119 });
120
121 $("input#search_'.$htmlnamejquery.'").autocomplete({
122 source: function( request, response ) {
123 $.get("'.$url.($urloption ? '?'.$urloption : '').'", { "'.str_replace('.', '_', $htmlname).'": request.term }, function(data){
124 if (data != null)
125 {
126 response($.map( data, function(item) {
127 if (autoselect == 1 && data.length == 1) {
128 $("#search_'.$htmlnamejquery.'").val(item.value);
129 $("#'.$htmlnamejquery.'").val(item.key).trigger("change");
130 }
131 var label = "";
132 if (item.label != null) {
133 label = item.label.toString();
134 }
135 var update = {};
136 if (options.update) {
137 $.each(options.update, function(key, value) {
138 update[key] = item[value];
139 });
140 }
141 var textarea = {};
142 if (options.update_textarea) {
143 $.each(options.update_textarea, function(key, value) {
144 textarea[key] = item[value];
145 });
146 }
147
148 console.log("Return value from GET to the rest of code");
149 return { label: label,
150 value: item.value,
151 id: item.key,
152 disabled: item.disabled,
153 update: update,
154 textarea: textarea,
155 pbq: item.pbq,
156 type: item.type,
157 qty: item.qty,
158 discount: item.discount,
159 pricebasetype: item.pricebasetype,
160 price_ht: item.price_ht,
161 price_ttc: item.price_ttc,
162 price_unit_ht: item.price_unit_ht,
163 price_unit_ht_locale: item.price_unit_ht_locale,
164 description : item.description,
165 ref_customer: item.ref_customer,
166 tva_tx: item.tva_tx,
167 default_vat_code: item.default_vat_code
168 }
169 }));
170 } else {
171 console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array.");
172 }
173 }, "json");
174 },
175 dataType: "json",
176 minLength: '.((int) $minLength).',
177 select: function( event, ui ) { // Function ran once new value has been selected into javascript combo
178 console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'");
179 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");
180
181 console.log("Propagate before some properties retrieved by ajax into data-xxx properties of #'.$htmlnamejquery.' component");
182 //console.log(ui.item);
183
184 // For supplier price and customer when price by quantity is off
185 $("#'.$htmlnamejquery.'").attr("data-up", ui.item.price_ht);
186 $("#'.$htmlnamejquery.'").attr("data-up-locale", ui.item.price_unit_ht_locale);
187 $("#'.$htmlnamejquery.'").attr("data-base", ui.item.pricebasetype);
188 $("#'.$htmlnamejquery.'").attr("data-qty", ui.item.qty);
189 $("#'.$htmlnamejquery.'").attr("data-discount", ui.item.discount);
190 $("#'.$htmlnamejquery.'").attr("data-description", ui.item.description);
191 $("#'.$htmlnamejquery.'").attr("data-ref-customer", ui.item.ref_customer);
192 $("#'.$htmlnamejquery.'").attr("data-tvatx", ui.item.tva_tx);
193 $("#'.$htmlnamejquery.'").attr("data-default-vat-code", ui.item.default_vat_code);
194 ';
195 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
196 $script .= '
197 // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on
198 console.log("PRODUIT_CUSTOMER_PRICES_BY_QTY is on, propagate also prices by quantity into data-pbqxxx properties");
199 $("#'.$htmlnamejquery.'").attr("data-pbq", ui.item.pbq);
200 $("#'.$htmlnamejquery.'").attr("data-pbqup", ui.item.price_ht);
201 $("#'.$htmlnamejquery.'").attr("data-pbqbase", ui.item.pricebasetype);
202 $("#'.$htmlnamejquery.'").attr("data-pbqqty", ui.item.qty);
203 $("#'.$htmlnamejquery.'").attr("data-pbqpercent", ui.item.discount);
204 ';
205 }
206 $script .= '
207 // A new value has been selected, we trigger the handlers on #htmlnamejquery
208 console.log("Trigger changes on #'.$htmlnamejquery.'");
209 $("#'.$htmlnamejquery.'").val(ui.item.id).trigger("change"); // Select new value
210
211 // Complementary actions
212
213 // Disable an element
214 if (options.option_disabled) {
215 console.log("Make action option_disabled on #"+options.option_disabled+" with disabled="+ui.item.disabled)
216 if (ui.item.disabled) {
217 $("#" + options.option_disabled).prop("disabled", true);
218 if (options.error) {
219 $.jnotify(options.error, "error", true); // Output with jnotify the error message
220 }
221 if (options.warning) {
222 $.jnotify(options.warning, "warning", false); // Output with jnotify the warning message
223 }
224 } else {
225 $("#" + options.option_disabled).removeAttr("disabled");
226 }
227 }
228
229 if (options.disabled) {
230 console.log("Make action disabled on each "+options.option_disabled)
231 $.each(options.disabled, function(key, value) {
232 $("#" + value).prop("disabled", true);
233 });
234 }
235 if (options.show) {
236 console.log("Make action show on each "+options.show)
237 $.each(options.show, function(key, value) {
238 $("#" + value).show().trigger("show");
239 });
240 }
241
242 // Update an input
243 if (ui.item.update) {
244 console.log("Make action update on each ui.item.update (if there is)")
245 // loop on each "update" fields
246 $.each(ui.item.update, function(key, value) {
247 console.log("Set value "+value+" into #"+key);
248 $("#" + key).val(value).trigger("change");
249 });
250 }
251 if (ui.item.textarea) {
252 console.log("Make action textarea on each ui.item.textarea (if there is)")
253 $.each(ui.item.textarea, function(key, value) {
254 if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
255 CKEDITOR.instances[key].setData(value);
256 CKEDITOR.instances[key].focus();
257 } else {
258 $("#" + key).html(value);
259 $("#" + key).focus();
260 }
261 });
262 }
263 console.log("ajax_autocompleter new value selected, we trigger change also on original component so on field #search_'.$htmlname.'");
264
265 $("#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.
266 }
267 ,delay: 500
268 }).data("'.$dataforrenderITem.'")._renderItem = function( ul, item ) {
269 return $("<li>")
270 .data( "'.$dataforitem.'", item ) // jQuery UI > 1.10.0
271 .append( \'<a><span class="tag">\' + item.label + "</span></a>" )
272 .appendTo(ul);
273 };
274
275 });';
276 $script .= '</script>';
277
278 return $script;
279}
280
295function ajax_multiautocompleter($htmlname, $fields, $url, $option = '', $minLength = 2, $autoselect = 0)
296{
297 $script = '<!-- Autocomplete -->'."\n";
298 $script .= '<script>';
299 $script .= 'jQuery(document).ready(function() {
300 var fields = '.json_encode($fields).';
301 var nboffields = fields.length;
302 var autoselect = '.$autoselect.';
303 //alert(fields + " " + nboffields);
304
305 jQuery("input#'.$htmlname.'").autocomplete({
306 dataType: "json",
307 minLength: '.$minLength.',
308 source: function( request, response ) {
309 jQuery.getJSON( "'.$url.($option ? '?'.$option : '').'", { '.$htmlname.': request.term }, function(data){
310 response( jQuery.map( data, function( item ) {
311 if (autoselect == 1 && data.length == 1) {
312 jQuery("#'.$htmlname.'").val(item.value);
313 // TODO move this to specific request
314 if (item.states) {
315 jQuery("#state_id").html(item.states);
316 }
317 for (i=0;i<nboffields;i++) {
318 if (item[fields[i]]) { // If defined
319 //alert(item[fields[i]]);
320 jQuery("#" + fields[i]).val(item[fields[i]]);
321 }
322 }
323 }
324 return item
325 }));
326 });
327 },
328 select: function( event, ui ) {
329 needtotrigger = "";
330 for (i=0;i<nboffields;i++) {
331 //alert(fields[i] + " = " + ui.item[fields[i]]);
332 if (fields[i]=="selectcountry_id")
333 {
334 if (ui.item[fields[i]] > 0) // Do not erase country if unknown
335 {
336 oldvalue=jQuery("#" + fields[i]).val();
337 newvalue=ui.item[fields[i]];
338 //alert(oldvalue+" "+newvalue);
339 jQuery("#" + fields[i]).val(ui.item[fields[i]]);
340 if (oldvalue != newvalue) // To force select2 to refresh visible content
341 {
342 needtotrigger="#" + fields[i];
343 }
344
345 // If we set new country and new state, we need to set a new list of state to allow change
346 if (ui.item.states && ui.item["state_id"] != jQuery("#state_id").value) {
347 jQuery("#state_id").html(ui.item.states);
348 }
349 }
350 }
351 else if (fields[i]=="state_id" || fields[i]=="state_id")
352 {
353 if (ui.item[fields[i]] > 0) // Do not erase state if unknown
354 {
355 oldvalue=jQuery("#" + fields[i]).val();
356 newvalue=ui.item[fields[i]];
357 //alert(oldvalue+" "+newvalue);
358 jQuery("#" + fields[i]).val(ui.item[fields[i]]); // This may fails if not correct country
359 if (oldvalue != newvalue) // To force select2 to refresh visible content
360 {
361 needtotrigger="#" + fields[i];
362 }
363 }
364 }
365 else if (ui.item[fields[i]]) { // If defined
366 oldvalue=jQuery("#" + fields[i]).val();
367 newvalue=ui.item[fields[i]];
368 //alert(oldvalue+" "+newvalue);
369 jQuery("#" + fields[i]).val(ui.item[fields[i]]);
370 if (oldvalue != newvalue) // To force select2 to refresh visible content
371 {
372 needtotrigger="#" + fields[i];
373 }
374 }
375
376 if (needtotrigger != "") // To force select2 to refresh visible content
377 {
378 // 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
379 // This is required for example when changing zip with autocomplete that change the country
380 jQuery(needtotrigger).delay(500).queue(function() {
381 jQuery(this).trigger("change");
382 });
383 }
384 }
385 }
386 });
387 });';
388 $script .= '</script>';
389
390 return $script;
391}
392
402function ajax_dialog($title, $message, $w = 350, $h = 150)
403{
404 global $langs;
405
406 $newtitle = dol_textishtml($title) ? dol_string_nohtmltag($title, 1) : $title;
407 $msg = '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
408 $msg .= $message;
409 $msg .= '</div>'."\n";
410 $msg .= '<script>
411 jQuery(function() {
412 jQuery("#dialog-info").dialog({
413 resizable: false,
414 height:'.$h.',
415 width:'.$w.',
416 modal: true,
417 buttons: {
418 Ok: function() {
419 jQuery(this).dialog(\'close\');
420 }
421 }
422 });
423 });
424 </script>';
425
426 $msg .= "\n";
427
428 return $msg;
429}
430
431
447function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = 0, $forcefocus = 0, $widthTypeOfAutocomplete = 'resolve', $idforemptyvalue = '-1', $morecss = '')
448{
449 global $conf;
450
451 // select2 can be disabled for smartphones
452 if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && getDolGlobalString('MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE')) {
453 return '';
454 }
455
456 if (getDolGlobalString('MAIN_DISABLE_AJAX_COMBOX')) {
457 return '';
458 }
459 if (empty($conf->use_javascript_ajax)) {
460 return '';
461 }
462 if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
463 return '';
464 }
465 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
466 return '';
467 }
468
469 if (empty($minLengthToAutocomplete)) {
470 $minLengthToAutocomplete = 0;
471 }
472
473 $moreselect2theme = ($morecss ? dol_escape_js(' '.$morecss) : '');
474 $moreselect2theme = preg_replace('/widthcentpercentminus[^\s]*/', '', $moreselect2theme);
475
476 $tmpplugin = 'select2';
477 $msg = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
478 <script>
479 $(document).ready(function () {
480 $(\''.(preg_match('/^\./', $htmlname) ? $htmlname : '#'.$htmlname).'\').'.$tmpplugin.'({
481 dir: \'ltr\',';
482 if (preg_match('/onrightofpage/', $morecss)) { // when $morecss contains 'onrightofpage', the select2 component must also be inside a parent with class="parentonrightofpage"
483 $msg .= ' dropdownAutoWidth: true, dropdownParent: $(\'#'.$htmlname.'\').parent(), '."\n";
484 }
485 $msg .= ' width: \''.dol_escape_js($widthTypeOfAutocomplete).'\', /* off or resolve */
486 minimumInputLength: '.((int) $minLengthToAutocomplete).',
487 language: select2arrayoflanguage,
488 matcher: function (params, data) {
489 if ($.trim(params.term) === "") {
490 return data;
491 }
492 keywords = (params.term).split(" ");
493 for (var i = 0; i < keywords.length; i++) {
494 if (((data.text).toUpperCase()).indexOf((keywords[i]).toUpperCase()) == -1) {
495 return null;
496 }
497 }
498 return data;
499 },
500 theme: \'default'.$moreselect2theme.'\', /* to add css on generated html components */
501 containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
502 selectionCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
503 dropdownCssClass: \'ui-dialog\',
504 templateResult: function (data, container) { /* Format visible output into combo list */
505 /* Code to add class of origin OPTION propagated to the new select2 <li> tag */
506 if (data.element) { $(container).addClass($(data.element).attr("class")); }
507 //console.log("data html is "+$(data.element).attr("data-html"));
508 if (data.id == '.((int) $idforemptyvalue).' && $(data.element).attr("data-html") == undefined) {
509 return \'&nbsp;\';
510 }
511 if ($(data.element).attr("data-html") != undefined) {
512 /* If property html set, we decode html entities and use this. */
513 /* Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, \'\', 0, 1) when building the select option. */
514 return htmlEntityDecodeJs($(data.element).attr("data-html"));
515 }
516 return data.text;
517 },
518 templateSelection: function (selection) { /* Format visible output of selected value */
519 if (selection.id == '.((int) $idforemptyvalue).') return \'<span class="placeholder">\'+selection.text+\'</span>\';
520 return selection.text;
521 },
522 escapeMarkup: function(markup) {
523 return markup;
524 }
525 })';
526 if ($forcefocus) {
527 $msg .= '.select2(\'focus\')';
528 }
529 $msg .= ';'."\n";
530
531 $msg .= '});'."\n";
532 $msg .= "</script>\n";
533
534 $msg .= ajax_event($htmlname, $events);
535
536 return $msg;
537}
538
539
548function ajax_event($htmlname, $events)
549{
550 $out = '';
551
552 if (is_array($events) && count($events)) { // If an array of js events to do were provided.
553 $out = '<!-- JS code to manage event for id = ' . $htmlname . ' -->
554 <script>
555 $(document).ready(function () {
556 jQuery("#'.$htmlname.'").change(function () {
557 var obj = '.json_encode($events) . ';
558 $.each(obj, function(key,values) {
559 if (values.method.length) {
560 runJsCodeForEvent'.$htmlname.'(values);
561 }
562 });
563 });
564 function runJsCodeForEvent'.$htmlname.'(obj) {
565 var id = $("#'.$htmlname.'").val();
566 var method = obj.method;
567 var url = obj.url;
568 var htmlname = obj.htmlname;
569 var showempty = obj.showempty;
570 console.log("Run runJsCodeForEvent-'.$htmlname.' from ajax_combobox id="+id+" method="+method+" showempty="+showempty+" url="+url+" htmlname="+htmlname);
571 $.getJSON(url,
572 {
573 action: method,
574 id: id,
575 htmlname: htmlname,
576 showempty: showempty
577 },
578 function(response) {
579 $.each(obj.params, function(key,action) {
580 if (key.length) {
581 var num = response.num;
582 if (num > 0) {
583 $("#" + key).removeAttr(action);
584 } else {
585 $("#" + key).attr(action, action);
586 }
587 }
588 });
589 $("select#" + htmlname).html(response.value);
590 if (response.num) {
591 var selecthtml_str = response.value;
592 var selecthtml_dom=$.parseHTML(selecthtml_str);
593 if (typeof(selecthtml_dom[0][0]) !== \'undefined\') {
594 $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML);
595 }
596 } else {
597 $("#inputautocomplete"+htmlname).val("");
598 }
599 $("select#" + htmlname).change(); /* Trigger event change */
600 }
601 );
602 }
603 });
604 </script>';
605 }
606
607 return $out;
608}
609
610
628function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0, $setzeroinsteadofdel = 0, $suffix = '', $mode = '', $morecss = 'inline-block')
629{
630 global $conf, $langs, $user;
631
632 $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity);
633 if (!isset($input)) {
634 $input = array();
635 }
636
637 if (empty($conf->use_javascript_ajax) || $forcenoajax) {
638 if (empty($conf->global->$code)) {
639 $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>';
640 } else {
641 $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>';
642 }
643 } else {
644 $out = "\n<!-- Ajax code to switch constant ".$code." -->".'
645 <script>
646 $(document).ready(function() {
647 var input = '.json_encode($input).';
648 var url = \''.DOL_URL_ROOT.'/core/ajax/constantonoff.php\';
649 var code = \''.dol_escape_js($code).'\';
650 var entity = \''.dol_escape_js($entity).'\';
651 var strict = \''.dol_escape_js($strict).'\';
652 var userid = \''.dol_escape_js($user->id).'\';
653 var yesButton = \''.dol_escape_js($langs->transnoentities("Yes")).'\';
654 var noButton = \''.dol_escape_js($langs->transnoentities("No")).'\';
655 var token = \''.currentToken().'\';
656
657 // Set constant
658 $("#set_" + code).click(function() {
659 if (input.alert && input.alert.set) {
660 if (input.alert.set.yesButton) yesButton = input.alert.set.yesButton;
661 if (input.alert.set.noButton) noButton = input.alert.set.noButton;
662 confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid, token);
663 } else {
664 setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);
665 }
666 });
667
668 // Del constant
669 $("#del_" + code).click(function() {
670 if (input.alert && input.alert.del) {
671 if (input.alert.del.yesButton) yesButton = input.alert.del.yesButton;
672 if (input.alert.del.noButton) noButton = input.alert.del.noButton;
673 confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid, token);
674 } else {';
675 if (empty($setzeroinsteadofdel)) {
676 $out .=' delConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);';
677 } else {
678 $out .=' setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 0);';
679 }
680 $out .= ' }
681 });
682 });
683 </script>'."\n";
684
685 $out .= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
686 $out .= '<span id="set_'.$code.'" class="valignmiddle inline-block 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>';
687 $out .= '<span id="del_'.$code.'" class="valignmiddle inline-block 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>';
688 $out .= "\n";
689 }
690
691 return $out;
692}
693
709function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array(), $morecss = '', $htmlname = '', $forcenojs = 0)
710{
711 global $conf, $langs;
712
713 if (empty($htmlname)) {
714 $htmlname = $code;
715 }
716 //var_dump($object->module); var_dump($object->element);
717
718 $out = '';
719
720 if (!empty($conf->use_javascript_ajax)) {
721 $out .= '<script>
722 $(function() {
723 var input = '.json_encode($input).';
724
725 // Set constant
726 $("#set_'.$htmlname.'_'.$object->id.'").click(function() {
727 console.log("Click managed by ajax_object_onoff");
728 $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
729 action: \'set\',
730 field: \''.dol_escape_js($field).'\',
731 value: \'1\',
732 element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
733 id: \''.((int) $object->id).'\',
734 token: \''.currentToken().'\'
735 },
736 function() {
737 $("#set_'.$htmlname.'_'.$object->id.'").hide();
738 $("#del_'.$htmlname.'_'.$object->id.'").show();
739 // Enable another element
740 if (input.disabled && input.disabled.length > 0) {
741 $.each(input.disabled, function(key,value) {
742 $("#" + value).removeAttr("disabled");
743 if ($("#" + value).hasClass("butActionRefused") == true) {
744 $("#" + value).removeClass("butActionRefused");
745 $("#" + value).addClass("butAction");
746 }
747 });
748 // Show another element
749 } else if (input.showhide && input.showhide.length > 0) {
750 $.each(input.showhide, function(key,value) {
751 $("#" + value).show();
752 });
753 }
754 });
755 });
756
757 // Del constant
758 $("#del_'.$htmlname.'_'.$object->id.'").click(function() {
759 console.log("Click managed by ajax_object_onoff");
760 $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
761 action: \'set\',
762 field: \''.dol_escape_js($field).'\',
763 value: \'0\',
764 element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
765 id: \''.((int) $object->id).'\',
766 token: \''.currentToken().'\'
767 },
768 function() {
769 $("#del_'.$htmlname.'_'.$object->id.'").hide();
770 $("#set_'.$htmlname.'_'.$object->id.'").show();
771 // Disable another element
772 if (input.disabled && input.disabled.length > 0) {
773 $.each(input.disabled, function(key,value) {
774 $("#" + value).prop("disabled", true);
775 if ($("#" + value).hasClass("butAction") == true) {
776 $("#" + value).removeClass("butAction");
777 $("#" + value).addClass("butActionRefused");
778 }
779 });
780 // Hide another element
781 } else if (input.showhide && input.showhide.length > 0) {
782 $.each(input.showhide, function(key,value) {
783 $("#" + value).hide();
784 });
785 }
786 });
787 });
788 });
789 </script>';
790 }
791
792 $switchon = 'switch_on';
793 $switchoff = 'switch_off';
794 $cssswitchon = '';
795 $cssswitchoff = '';
796 $tmparray = explode(':', $text_on);
797 if (!empty($tmparray[1])) {
798 $text_on = $tmparray[0];
799 $switchon = $tmparray[1];
800 if (!empty($tmparray[2])) {
801 $cssswitchon = $tmparray[2];
802 }
803 }
804 $tmparray = explode(':', $text_off);
805 if (!empty($tmparray[1])) {
806 $text_off = $tmparray[0];
807 $switchoff = $tmparray[1];
808 if (!empty($tmparray[2])) {
809 $cssswitchoff = $tmparray[2];
810 }
811 }
812
813 if (empty($conf->use_javascript_ajax) || $forcenojs) {
814 $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>';
815 $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>';
816 } else {
817 $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>';
818 $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>';
819 }
820
821 return $out;
822}
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:447
ajax_dialog($title, $message, $w=350, $h=150)
Show an ajax dialog.
Definition ajax.lib.php:402
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:295
ajax_event($htmlname, $events)
Add event management script.
Definition ajax.lib.php:548
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.