ajax.lib.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. /**
  21. * \file htdocs/core/lib/ajax.lib.php
  22. * \brief Page called to enhance interface with Javascript and Ajax features.
  23. */
  24. /**
  25. * Generic function that return javascript to add to a page to transform a common input field into an autocomplete field by calling an Ajax page (ex: /societe/ajax/ajaxcompanies.php).
  26. * The HTML field must be an input text with id=search_$htmlname.
  27. * This use the jQuery "autocomplete" function. If we want to use the select2, we must also convert the input into select on funcntions that call this method.
  28. *
  29. * @param string $selected Preselected value
  30. * @param string $htmlname HTML name of input field
  31. * @param string $url Ajax Url to call for request: /path/page.php. Must return a json array ('key'=>id, 'value'=>String shown into input field once selected, 'label'=>String shown into combo list)
  32. * @param string $urloption More parameters on URL request
  33. * @param int $minLength Minimum number of chars to trigger that Ajax search
  34. * @param int $autoselect Automatic selection if just one value (trigger("change") on field is done if search return only 1 result)
  35. * @param array $ajaxoptions Multiple options array
  36. * - Ex: array('update'=>array('field1','field2'...)) will reset field1 and field2 once select done
  37. * - Ex: array('disabled'=> )
  38. * - Ex: array('show'=> )
  39. * - Ex: array('update_textarea'=> )
  40. * - Ex: array('option_disabled'=> id to disable and warning to show if we select a disabled value (this is possible when using autocomplete ajax)
  41. * @param string $moreparams More params provided to ajax call
  42. * @return string Script
  43. */
  44. function ajax_autocompleter($selected, $htmlname, $url, $urloption = '', $minLength = 2, $autoselect = 0, $ajaxoptions = array(), $moreparams = '')
  45. {
  46. global $conf;
  47. if (empty($minLength)) {
  48. $minLength = 1;
  49. }
  50. $dataforrenderITem = 'ui-autocomplete';
  51. $dataforitem = 'ui-autocomplete-item';
  52. // Allow two constant to use other values for backward compatibility
  53. if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) {
  54. $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
  55. }
  56. if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) {
  57. $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM');
  58. }
  59. $htmlnamejquery = str_replace('.', '\\\\.', $htmlname);
  60. // Input search_htmlname is original field
  61. // Input htmlname is a second input field used when using ajax autocomplete.
  62. $script = '<input type="hidden" name="'.$htmlname.'" id="'.$htmlname.'" value="'.$selected.'" '.($moreparams ? $moreparams : '').' />';
  63. $script .= '<!-- Javascript code for autocomplete of field '.$htmlname.' -->'."\n";
  64. $script .= '<script>'."\n";
  65. $script .= '$(document).ready(function() {
  66. var autoselect = '.((int) $autoselect).';
  67. var options = '.json_encode($ajaxoptions).'; /* Option of actions to do after keyup, or after select */
  68. /* 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 */
  69. $("input#search_'.$htmlnamejquery.'").keydown(function(e) {
  70. if (e.keyCode != 9) /* If not "Tab" key */
  71. {
  72. if (e.keyCode == 13) { return false; } /* disable "ENTER" key useful for barcode readers */
  73. console.log("Clear id previously selected for field '.$htmlname.'");
  74. $("#'.$htmlnamejquery.'").val("");
  75. }
  76. });
  77. // Check options for secondary actions when keyup
  78. $("input#search_'.$htmlnamejquery.'").keyup(function() {
  79. if ($(this).val().length == 0)
  80. {
  81. $("#search_'.$htmlnamejquery.'").val("");
  82. $("#'.$htmlnamejquery.'").val("").trigger("change");
  83. if (options.option_disabled) {
  84. $("#" + options.option_disabled).removeAttr("disabled");
  85. }
  86. if (options.disabled) {
  87. $.each(options.disabled, function(key, value) {
  88. $("#" + value).removeAttr("disabled");
  89. });
  90. }
  91. if (options.update) {
  92. $.each(options.update, function(key, value) {
  93. $("#" + key).val("").trigger("change");
  94. });
  95. }
  96. if (options.show) {
  97. $.each(options.show, function(key, value) {
  98. $("#" + value).hide().trigger("hide");
  99. });
  100. }
  101. if (options.update_textarea) {
  102. $.each(options.update_textarea, function(key, value) {
  103. if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
  104. CKEDITOR.instances[key].setData("");
  105. } else {
  106. $("#" + key).html("");
  107. }
  108. });
  109. }
  110. }
  111. });
  112. $("input#search_'.$htmlnamejquery.'").autocomplete({
  113. source: function( request, response ) {
  114. $.get("'.$url.($urloption ? '?'.$urloption : '').'", { "'.str_replace('.', '_', $htmlname).'": request.term }, function(data){
  115. if (data != null)
  116. {
  117. response($.map( data, function(item) {
  118. if (autoselect == 1 && data.length == 1) {
  119. $("#search_'.$htmlnamejquery.'").val(item.value);
  120. $("#'.$htmlnamejquery.'").val(item.key).trigger("change");
  121. }
  122. var label = item.label.toString();
  123. var update = {};
  124. if (options.update) {
  125. $.each(options.update, function(key, value) {
  126. update[key] = item[value];
  127. });
  128. }
  129. var textarea = {};
  130. if (options.update_textarea) {
  131. $.each(options.update_textarea, function(key, value) {
  132. textarea[key] = item[value];
  133. });
  134. }
  135. return { label: label, value: item.value, id: item.key, disabled: item.disabled,
  136. update: update, textarea: textarea,
  137. pbq: item.pbq,
  138. type: item.type, qty: item.qty, discount: item.discount,
  139. pricebasetype: item.pricebasetype,
  140. price_ht: item.price_ht,
  141. price_ttc: item.price_ttc,
  142. description : item.description,
  143. ref_customer: item.ref_customer }
  144. }));
  145. } else {
  146. console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array.");
  147. }
  148. }, "json");
  149. },
  150. dataType: "json",
  151. minLength: '.((int) $minLength).',
  152. select: function( event, ui ) { // Function ran once new value has been selected into javascript combo
  153. console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'");
  154. 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");
  155. console.log("Propagate before some properties retrieved by ajax into data-xxx properties");
  156. // For supplier price and customer when price by quantity is off
  157. $("#'.$htmlnamejquery.'").attr("data-up", ui.item.price_ht);
  158. $("#'.$htmlnamejquery.'").attr("data-base", ui.item.pricebasetype);
  159. $("#'.$htmlnamejquery.'").attr("data-qty", ui.item.qty);
  160. $("#'.$htmlnamejquery.'").attr("data-discount", ui.item.discount);
  161. $("#'.$htmlnamejquery.'").attr("data-description", ui.item.description);
  162. $("#'.$htmlnamejquery.'").attr("data-ref-customer", ui.item.ref_customer);
  163. ';
  164. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
  165. $script .= '
  166. // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on
  167. $("#'.$htmlnamejquery.'").attr("data-pbq", ui.item.pbq);
  168. $("#'.$htmlnamejquery.'").attr("data-pbqup", ui.item.price_ht);
  169. $("#'.$htmlnamejquery.'").attr("data-pbqbase", ui.item.pricebasetype);
  170. $("#'.$htmlnamejquery.'").attr("data-pbqqty", ui.item.qty);
  171. $("#'.$htmlnamejquery.'").attr("data-pbqpercent", ui.item.discount);
  172. ';
  173. }
  174. $script .= '
  175. $("#'.$htmlnamejquery.'").val(ui.item.id).trigger("change"); // Select new value
  176. // Disable an element
  177. if (options.option_disabled) {
  178. console.log("Make action option_disabled on #"+options.option_disabled+" with disabled="+ui.item.disabled)
  179. if (ui.item.disabled) {
  180. $("#" + options.option_disabled).prop("disabled", true);
  181. if (options.error) {
  182. $.jnotify(options.error, "error", true); // Output with jnotify the error message
  183. }
  184. if (options.warning) {
  185. $.jnotify(options.warning, "warning", false); // Output with jnotify the warning message
  186. }
  187. } else {
  188. $("#" + options.option_disabled).removeAttr("disabled");
  189. }
  190. }
  191. if (options.disabled) {
  192. console.log("Make action disabled on each "+options.option_disabled)
  193. $.each(options.disabled, function(key, value) {
  194. $("#" + value).prop("disabled", true);
  195. });
  196. }
  197. if (options.show) {
  198. console.log("Make action show on each "+options.show)
  199. $.each(options.show, function(key, value) {
  200. $("#" + value).show().trigger("show");
  201. });
  202. }
  203. // Update an input
  204. if (ui.item.update) {
  205. console.log("Make action update on each ui.item.update")
  206. // loop on each "update" fields
  207. $.each(ui.item.update, function(key, value) {
  208. console.log("Set value "+value+" into #"+key);
  209. $("#" + key).val(value).trigger("change");
  210. });
  211. }
  212. if (ui.item.textarea) {
  213. console.log("Make action textarea on each ui.item.textarea")
  214. $.each(ui.item.textarea, function(key, value) {
  215. if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
  216. CKEDITOR.instances[key].setData(value);
  217. CKEDITOR.instances[key].focus();
  218. } else {
  219. $("#" + key).html(value);
  220. $("#" + key).focus();
  221. }
  222. });
  223. }
  224. console.log("ajax_autocompleter new value selected, we trigger change also on original component so on field #search_'.$htmlname.'");
  225. $("#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.
  226. }
  227. ,delay: 500
  228. }).data("'.$dataforrenderITem.'")._renderItem = function( ul, item ) {
  229. return $("<li>")
  230. .data( "'.$dataforitem.'", item ) // jQuery UI > 1.10.0
  231. .append( \'<a><span class="tag">\' + item.label + "</span></a>" )
  232. .appendTo(ul);
  233. };
  234. });';
  235. $script .= '</script>';
  236. return $script;
  237. }
  238. /**
  239. * Generic function that return javascript to add to a page to transform a common input field into an autocomplete field by calling an Ajax page (ex: core/ajax/ziptown.php).
  240. * The Ajax page can also returns several values (json format) to fill several input fields.
  241. * The HTML field must be an input text with id=$htmlname.
  242. * This use the jQuery "autocomplete" function.
  243. *
  244. * @param string $htmlname HTML name of input field
  245. * @param array $fields Array of key of fields to autocomplete
  246. * @param string $url URL for ajax request : /chemin/fichier.php
  247. * @param string $option More parameters on URL request
  248. * @param int $minLength Minimum number of chars to trigger that Ajax search
  249. * @param int $autoselect Automatic selection if just one value
  250. * @return string Script
  251. */
  252. function ajax_multiautocompleter($htmlname, $fields, $url, $option = '', $minLength = 2, $autoselect = 0)
  253. {
  254. $script = '<!-- Autocomplete -->'."\n";
  255. $script .= '<script>';
  256. $script .= 'jQuery(document).ready(function() {
  257. var fields = '.json_encode($fields).';
  258. var nboffields = fields.length;
  259. var autoselect = '.$autoselect.';
  260. //alert(fields + " " + nboffields);
  261. jQuery("input#'.$htmlname.'").autocomplete({
  262. dataType: "json",
  263. minLength: '.$minLength.',
  264. source: function( request, response ) {
  265. jQuery.getJSON( "'.$url.($option ? '?'.$option : '').'", { '.$htmlname.': request.term }, function(data){
  266. response( jQuery.map( data, function( item ) {
  267. if (autoselect == 1 && data.length == 1) {
  268. jQuery("#'.$htmlname.'").val(item.value);
  269. // TODO move this to specific request
  270. if (item.states) {
  271. jQuery("#state_id").html(item.states);
  272. }
  273. for (i=0;i<nboffields;i++) {
  274. if (item[fields[i]]) { // If defined
  275. //alert(item[fields[i]]);
  276. jQuery("#" + fields[i]).val(item[fields[i]]);
  277. }
  278. }
  279. }
  280. return item
  281. }));
  282. });
  283. },
  284. select: function( event, ui ) {
  285. needtotrigger = "";
  286. for (i=0;i<nboffields;i++) {
  287. //alert(fields[i] + " = " + ui.item[fields[i]]);
  288. if (fields[i]=="selectcountry_id")
  289. {
  290. if (ui.item[fields[i]] > 0) // Do not erase country if unknown
  291. {
  292. oldvalue=jQuery("#" + fields[i]).val();
  293. newvalue=ui.item[fields[i]];
  294. //alert(oldvalue+" "+newvalue);
  295. jQuery("#" + fields[i]).val(ui.item[fields[i]]);
  296. if (oldvalue != newvalue) // To force select2 to refresh visible content
  297. {
  298. needtotrigger="#" + fields[i];
  299. }
  300. // If we set new country and new state, we need to set a new list of state to allow change
  301. if (ui.item.states && ui.item["state_id"] != jQuery("#state_id").value) {
  302. jQuery("#state_id").html(ui.item.states);
  303. }
  304. }
  305. }
  306. else if (fields[i]=="state_id" || fields[i]=="state_id")
  307. {
  308. if (ui.item[fields[i]] > 0) // Do not erase state if unknown
  309. {
  310. oldvalue=jQuery("#" + fields[i]).val();
  311. newvalue=ui.item[fields[i]];
  312. //alert(oldvalue+" "+newvalue);
  313. jQuery("#" + fields[i]).val(ui.item[fields[i]]); // This may fails if not correct country
  314. if (oldvalue != newvalue) // To force select2 to refresh visible content
  315. {
  316. needtotrigger="#" + fields[i];
  317. }
  318. }
  319. }
  320. else if (ui.item[fields[i]]) { // If defined
  321. oldvalue=jQuery("#" + fields[i]).val();
  322. newvalue=ui.item[fields[i]];
  323. //alert(oldvalue+" "+newvalue);
  324. jQuery("#" + fields[i]).val(ui.item[fields[i]]);
  325. if (oldvalue != newvalue) // To force select2 to refresh visible content
  326. {
  327. needtotrigger="#" + fields[i];
  328. }
  329. }
  330. if (needtotrigger != "") // To force select2 to refresh visible content
  331. {
  332. // 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
  333. // This is required for example when changing zip with autocomplete that change the country
  334. jQuery(needtotrigger).delay(500).queue(function() {
  335. jQuery(this).trigger("change");
  336. });
  337. }
  338. }
  339. }
  340. });
  341. });';
  342. $script .= '</script>';
  343. return $script;
  344. }
  345. /**
  346. * Show an ajax dialog
  347. *
  348. * @param string $title Title of dialog box
  349. * @param string $message Message of dialog box
  350. * @param int $w Width of dialog box
  351. * @param int $h height of dialog box
  352. * @return string
  353. */
  354. function ajax_dialog($title, $message, $w = 350, $h = 150)
  355. {
  356. global $langs;
  357. $newtitle = dol_textishtml($title) ?dol_string_nohtmltag($title, 1) : $title;
  358. $msg = '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
  359. $msg .= $message;
  360. $msg .= '</div>'."\n";
  361. $msg .= '<script>
  362. jQuery(function() {
  363. jQuery("#dialog-info").dialog({
  364. resizable: false,
  365. height:'.$h.',
  366. width:'.$w.',
  367. modal: true,
  368. buttons: {
  369. Ok: function() {
  370. jQuery(this).dialog(\'close\');
  371. }
  372. }
  373. });
  374. });
  375. </script>';
  376. $msg .= "\n";
  377. return $msg;
  378. }
  379. /**
  380. * Convert a html select field into an ajax combobox.
  381. * Use ajax_combobox() only for small combo list! If not, use instead ajax_autocompleter().
  382. * TODO: It is used when COMPANY_USE_SEARCH_TO_SELECT and CONTACT_USE_SEARCH_TO_SELECT are set by html.formcompany.class.php. Should use ajax_autocompleter instead like done by html.form.class.php for select_produits.
  383. *
  384. * @param string $htmlname Name of html select field ('myid' or '.myclass')
  385. * @param array $events More events option. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  386. * @param int $minLengthToAutocomplete Minimum length of input string to start autocomplete
  387. * @param int $forcefocus Force focus on field
  388. * @param string $widthTypeOfAutocomplete 'resolve' or 'off'
  389. * @param string $idforemptyvalue '-1'
  390. * @return string Return html string to convert a select field into a combo, or '' if feature has been disabled for some reason.
  391. * @see selectArrayAjax() of html.form.class
  392. */
  393. function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = 0, $forcefocus = 0, $widthTypeOfAutocomplete = 'resolve', $idforemptyvalue = '-1')
  394. {
  395. global $conf;
  396. // select2 can be disabled for smartphones
  397. if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && !empty($conf->global->MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE)) {
  398. return '';
  399. }
  400. if (!empty($conf->global->MAIN_DISABLE_AJAX_COMBOX)) {
  401. return '';
  402. }
  403. if (empty($conf->use_javascript_ajax)) {
  404. return '';
  405. }
  406. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  407. return '';
  408. }
  409. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  410. return '';
  411. }
  412. if (empty($minLengthToAutocomplete)) {
  413. $minLengthToAutocomplete = 0;
  414. }
  415. $tmpplugin = 'select2';
  416. $msg = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
  417. <script>
  418. $(document).ready(function () {
  419. $(\''.(preg_match('/^\./', $htmlname) ? $htmlname : '#'.$htmlname).'\').'.$tmpplugin.'({
  420. dir: \'ltr\',
  421. width: \''.$widthTypeOfAutocomplete.'\', /* off or resolve */
  422. minimumInputLength: '.$minLengthToAutocomplete.',
  423. language: select2arrayoflanguage,
  424. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  425. selectionCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  426. templateResult: function (data, container) { /* Format visible output into combo list */
  427. /* Code to add class of origin OPTION propagated to the new select2 <li> tag */
  428. if (data.element) { $(container).addClass($(data.element).attr("class")); }
  429. //console.log($(data.element).attr("data-html"));
  430. if (data.id == '.((int) $idforemptyvalue).' && $(data.element).attr("data-html") == undefined) {
  431. return \'&nbsp;\';
  432. }
  433. if ($(data.element).attr("data-html") != undefined) return htmlEntityDecodeJs($(data.element).attr("data-html")); // If property html set, we decode html entities and use this
  434. return data.text;
  435. },
  436. templateSelection: function (selection) { /* Format visible output of selected value */
  437. if (selection.id == '.((int) $idforemptyvalue).') return \'<span class="placeholder">\'+selection.text+\'</span>\';
  438. return selection.text;
  439. },
  440. escapeMarkup: function(markup) {
  441. return markup;
  442. },
  443. dropdownCssClass: \'ui-dialog\'
  444. })';
  445. if ($forcefocus) {
  446. $msg .= '.select2(\'focus\')';
  447. }
  448. $msg .= ';'."\n";
  449. if (is_array($events) && count($events)) { // If an array of js events to do were provided.
  450. $msg .= '
  451. jQuery("#'.$htmlname.'").change(function () {
  452. var obj = '.json_encode($events).';
  453. $.each(obj, function(key,values) {
  454. if (values.method.length) {
  455. runJsCodeForEvent'.$htmlname.'(values);
  456. }
  457. });
  458. });
  459. function runJsCodeForEvent'.$htmlname.'(obj) {
  460. var id = $("#'.$htmlname.'").val();
  461. var method = obj.method;
  462. var url = obj.url;
  463. var htmlname = obj.htmlname;
  464. var showempty = obj.showempty;
  465. console.log("Run runJsCodeForEvent-'.$htmlname.' from ajax_combobox id="+id+" method="+method+" showempty="+showempty+" url="+url+" htmlname="+htmlname);
  466. $.getJSON(url,
  467. {
  468. action: method,
  469. id: id,
  470. htmlname: htmlname,
  471. showempty: showempty
  472. },
  473. function(response) {
  474. $.each(obj.params, function(key,action) {
  475. if (key.length) {
  476. var num = response.num;
  477. if (num > 0) {
  478. $("#" + key).removeAttr(action);
  479. } else {
  480. $("#" + key).attr(action, action);
  481. }
  482. }
  483. });
  484. $("select#" + htmlname).html(response.value);
  485. if (response.num) {
  486. var selecthtml_str = response.value;
  487. var selecthtml_dom=$.parseHTML(selecthtml_str);
  488. if (typeof(selecthtml_dom[0][0]) !== \'undefined\') {
  489. $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML);
  490. }
  491. } else {
  492. $("#inputautocomplete"+htmlname).val("");
  493. }
  494. $("select#" + htmlname).change(); /* Trigger event change */
  495. }
  496. );
  497. }';
  498. }
  499. $msg .= '});'."\n";
  500. $msg .= "</script>\n";
  501. return $msg;
  502. }
  503. /**
  504. * On/off button for constant
  505. *
  506. * @param string $code Name of constant
  507. * @param array $input Array of complementary actions to do if success ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid'))
  508. * @param int $entity Entity. Current entity is used if null.
  509. * @param int $revertonoff 1=Revert on/off
  510. * @param int $strict Use only "disabled" with delConstant and "enabled" with setConstant
  511. * @param int $forcereload Force to reload page if we click/change value (this is supported only when there is no 'alert' option in input)
  512. * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No left margin.
  513. * @param int $forcenoajax 1 = Force to use a ahref link instead of ajax code.
  514. * @param int $setzeroinsteadofdel 1 = Set constantto '0' instead of deleting it
  515. * @param string $suffix Suffix to use on the name of the switch_on picto. Example: '', '_red'
  516. * @param string $mode Add parameter &mode= to the href link (Used for href link)
  517. * @return string
  518. */
  519. function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0, $setzeroinsteadofdel = 0, $suffix = '', $mode = '')
  520. {
  521. global $conf, $langs, $user;
  522. $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity);
  523. if (!isset($input)) {
  524. $input = array();
  525. }
  526. if (empty($conf->use_javascript_ajax) || $forcenoajax) {
  527. if (empty($conf->global->$code)) {
  528. print '<a 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>';
  529. } else {
  530. print '<a 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>';
  531. }
  532. } else {
  533. $out = "\n<!-- Ajax code to switch constant ".$code." -->".'
  534. <script>
  535. $(document).ready(function() {
  536. var input = '.json_encode($input).';
  537. var url = \''.DOL_URL_ROOT.'/core/ajax/constantonoff.php\';
  538. var code = \''.dol_escape_js($code).'\';
  539. var entity = \''.dol_escape_js($entity).'\';
  540. var strict = \''.dol_escape_js($strict).'\';
  541. var userid = \''.dol_escape_js($user->id).'\';
  542. var yesButton = \''.dol_escape_js($langs->transnoentities("Yes")).'\';
  543. var noButton = \''.dol_escape_js($langs->transnoentities("No")).'\';
  544. var token = \''.currentToken().'\';
  545. // Set constant
  546. $("#set_" + code).click(function() {
  547. if (input.alert && input.alert.set) {
  548. if (input.alert.set.yesButton) yesButton = input.alert.set.yesButton;
  549. if (input.alert.set.noButton) noButton = input.alert.set.noButton;
  550. confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid, token);
  551. } else {
  552. setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);
  553. }
  554. });
  555. // Del constant
  556. $("#del_" + code).click(function() {
  557. if (input.alert && input.alert.del) {
  558. if (input.alert.del.yesButton) yesButton = input.alert.del.yesButton;
  559. if (input.alert.del.noButton) noButton = input.alert.del.noButton;
  560. confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid, token);
  561. } else {';
  562. if (empty($setzeroinsteadofdel)) {
  563. $out .=' delConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);';
  564. } else {
  565. $out .=' setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 0);';
  566. }
  567. $out .= ' }
  568. });
  569. });
  570. </script>'."\n";
  571. $out .= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
  572. $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>';
  573. $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>';
  574. $out .= "\n";
  575. }
  576. return $out;
  577. }
  578. /**
  579. * On/off button to change status of an object
  580. * This is called when MAIN_DIRECT_STATUS_UPDATE is set and it use tha ajax service objectonoff.php
  581. *
  582. * @param Object $object Object to set
  583. * @param string $code Name of constant : status or status_buy for product by example
  584. * @param string $field Name of database field : 'tosell' or 'tobuy' for product by example
  585. * @param string $text_on Text if on
  586. * @param string $text_off Text if off
  587. * @param array $input Array of type->list of CSS element to switch. Example: array('disabled'=>array(0=>'cssid'))
  588. * @param string $morecss More CSS
  589. * @return string html for button on/off
  590. */
  591. function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array(), $morecss = '')
  592. {
  593. global $langs;
  594. $out = '<script>
  595. $(function() {
  596. var input = '.json_encode($input).';
  597. // Set constant
  598. $("#set_'.$code.'_'.$object->id.'").click(function() {
  599. $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
  600. action: \'set\',
  601. field: \''.$field.'\',
  602. value: \'1\',
  603. element: \''.$object->element.'\',
  604. id: \''.$object->id.'\',
  605. token: \''.newToken().'\'
  606. },
  607. function() {
  608. $("#set_'.$code.'_'.$object->id.'").hide();
  609. $("#del_'.$code.'_'.$object->id.'").show();
  610. // Enable another element
  611. if (input.disabled && input.disabled.length > 0) {
  612. $.each(input.disabled, function(key,value) {
  613. $("#" + value).removeAttr("disabled");
  614. if ($("#" + value).hasClass("butActionRefused") == true) {
  615. $("#" + value).removeClass("butActionRefused");
  616. $("#" + value).addClass("butAction");
  617. }
  618. });
  619. // Show another element
  620. } else if (input.showhide && input.showhide.length > 0) {
  621. $.each(input.showhide, function(key,value) {
  622. $("#" + value).show();
  623. });
  624. }
  625. });
  626. });
  627. // Del constant
  628. $("#del_'.$code.'_'.$object->id.'").click(function() {
  629. $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
  630. action: \'set\',
  631. field: \''.$field.'\',
  632. value: \'0\',
  633. element: \''.$object->element.'\',
  634. id: \''.$object->id.'\',
  635. token: \''.newToken().'\'
  636. },
  637. function() {
  638. $("#del_'.$code.'_'.$object->id.'").hide();
  639. $("#set_'.$code.'_'.$object->id.'").show();
  640. // Disable another element
  641. if (input.disabled && input.disabled.length > 0) {
  642. $.each(input.disabled, function(key,value) {
  643. $("#" + value).prop("disabled", true);
  644. if ($("#" + value).hasClass("butAction") == true) {
  645. $("#" + value).removeClass("butAction");
  646. $("#" + value).addClass("butActionRefused");
  647. }
  648. });
  649. // Hide another element
  650. } else if (input.showhide && input.showhide.length > 0) {
  651. $.each(input.showhide, function(key,value) {
  652. $("#" + value).hide();
  653. });
  654. }
  655. });
  656. });
  657. });
  658. </script>';
  659. $out .= '<span id="set_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? 'hideobject' : '').($morecss ? ' '.$morecss : '').'">'.img_picto($langs->trans($text_off), 'switch_off').'</span>';
  660. $out .= '<span id="del_'.$code.'_'.$object->id.'" class="linkobject '.($object->$code == 1 ? '' : 'hideobject').($morecss ? ' '.$morecss : '').'">'.img_picto($langs->trans($text_on), 'switch_on').'</span>';
  661. return $out;
  662. }