ajax.lib.php 32 KB

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