ajax.lib.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. if (empty($minLength)) {
  47. $minLength = 1;
  48. }
  49. $dataforrenderITem = 'ui-autocomplete';
  50. $dataforitem = 'ui-autocomplete-item';
  51. // Allow two constant to use other values for backward compatibility
  52. if (defined('JS_QUERY_AUTOCOMPLETE_RENDERITEM')) {
  53. $dataforrenderITem = constant('JS_QUERY_AUTOCOMPLETE_RENDERITEM');
  54. }
  55. if (defined('JS_QUERY_AUTOCOMPLETE_ITEM')) {
  56. $dataforitem = constant('JS_QUERY_AUTOCOMPLETE_ITEM');
  57. }
  58. $htmlnamejquery = str_replace('.', '\\\\.', $htmlname);
  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_'.$htmlnamejquery.'").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. $("#'.$htmlnamejquery.'").val("");
  74. $(\'input[name="'.$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 = "";
  123. if (item.label != null) {
  124. label = item.label.toString();
  125. }
  126. var update = {};
  127. if (options.update) {
  128. $.each(options.update, function(key, value) {
  129. update[key] = item[value];
  130. });
  131. }
  132. var textarea = {};
  133. if (options.update_textarea) {
  134. $.each(options.update_textarea, function(key, value) {
  135. textarea[key] = item[value];
  136. });
  137. }
  138. console.log("Return value from GET to the rest of code");
  139. return { label: label,
  140. value: item.value,
  141. id: item.key,
  142. disabled: item.disabled,
  143. update: update,
  144. textarea: textarea,
  145. pbq: item.pbq,
  146. type: item.type,
  147. qty: item.qty,
  148. discount: item.discount,
  149. pricebasetype: item.pricebasetype,
  150. price_ht: item.price_ht,
  151. price_ttc: item.price_ttc,
  152. price_unit_ht: item.price_unit_ht,
  153. price_unit_ht_locale: item.price_unit_ht_locale,
  154. description : item.description,
  155. ref_customer: item.ref_customer,
  156. tva_tx: item.tva_tx,
  157. default_vat_code: item.default_vat_code
  158. }
  159. }));
  160. } else {
  161. console.error("Error: Ajax url '.$url.($urloption ? '?'.$urloption : '').' has returned an empty page. Should be an empty json array.");
  162. }
  163. }, "json");
  164. },
  165. dataType: "json",
  166. minLength: '.((int) $minLength).',
  167. select: function( event, ui ) { // Function ran once new value has been selected into javascript combo
  168. console.log("We will trigger change on input '.$htmlname.' because of the select definition of autocomplete code for input#search_'.$htmlname.'");
  169. 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");
  170. console.log("Propagate before some properties retrieved by ajax into data-xxx properties of #'.$htmlnamejquery.' component");
  171. //console.log(ui.item);
  172. // For supplier price and customer when price by quantity is off
  173. $("#'.$htmlnamejquery.'").attr("data-up", ui.item.price_ht);
  174. $("#'.$htmlnamejquery.'").attr("data-up-locale", ui.item.price_unit_ht_locale);
  175. $("#'.$htmlnamejquery.'").attr("data-base", ui.item.pricebasetype);
  176. $("#'.$htmlnamejquery.'").attr("data-qty", ui.item.qty);
  177. $("#'.$htmlnamejquery.'").attr("data-discount", ui.item.discount);
  178. $("#'.$htmlnamejquery.'").attr("data-description", ui.item.description);
  179. $("#'.$htmlnamejquery.'").attr("data-ref-customer", ui.item.ref_customer);
  180. $("#'.$htmlnamejquery.'").attr("data-tvatx", ui.item.tva_tx);
  181. $("#'.$htmlnamejquery.'").attr("data-default-vat-code", ui.item.default_vat_code);
  182. ';
  183. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  184. $script .= '
  185. // For customer price when PRODUIT_CUSTOMER_PRICES_BY_QTY is on
  186. console.log("PRODUIT_CUSTOMER_PRICES_BY_QTY is on, propagate also prices by quantity into data-pbqxxx properties");
  187. $("#'.$htmlnamejquery.'").attr("data-pbq", ui.item.pbq);
  188. $("#'.$htmlnamejquery.'").attr("data-pbqup", ui.item.price_ht);
  189. $("#'.$htmlnamejquery.'").attr("data-pbqbase", ui.item.pricebasetype);
  190. $("#'.$htmlnamejquery.'").attr("data-pbqqty", ui.item.qty);
  191. $("#'.$htmlnamejquery.'").attr("data-pbqpercent", ui.item.discount);
  192. ';
  193. }
  194. $script .= '
  195. // A new value has been selected, we trigger the handlers on #htmlnamejquery
  196. console.log("Trigger changes on #'.$htmlnamejquery.'");
  197. $("#'.$htmlnamejquery.'").val(ui.item.id).trigger("change"); // Select new value
  198. $(\'input[name="'.$htmlnamejquery.'"]\').val(ui.item.id).trigger("change");
  199. // Complementary actions
  200. // Disable an element
  201. if (options.option_disabled) {
  202. console.log("Make action option_disabled on #"+options.option_disabled+" with disabled="+ui.item.disabled)
  203. if (ui.item.disabled) {
  204. $("#" + options.option_disabled).prop("disabled", true);
  205. if (options.error) {
  206. $.jnotify(options.error, "error", true); // Output with jnotify the error message
  207. }
  208. if (options.warning) {
  209. $.jnotify(options.warning, "warning", false); // Output with jnotify the warning message
  210. }
  211. } else {
  212. $("#" + options.option_disabled).removeAttr("disabled");
  213. }
  214. }
  215. if (options.disabled) {
  216. console.log("Make action disabled on each "+options.option_disabled)
  217. $.each(options.disabled, function(key, value) {
  218. $("#" + value).prop("disabled", true);
  219. });
  220. }
  221. if (options.show) {
  222. console.log("Make action show on each "+options.show)
  223. $.each(options.show, function(key, value) {
  224. $("#" + value).show().trigger("show");
  225. });
  226. }
  227. // Update an input
  228. if (ui.item.update) {
  229. console.log("Make action update on each ui.item.update (if there is)")
  230. // loop on each "update" fields
  231. $.each(ui.item.update, function(key, value) {
  232. console.log("Set value "+value+" into #"+key);
  233. $("#" + key).val(value).trigger("change");
  234. });
  235. }
  236. if (ui.item.textarea) {
  237. console.log("Make action textarea on each ui.item.textarea (if there is)")
  238. $.each(ui.item.textarea, function(key, value) {
  239. if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined" && CKEDITOR.instances[key] != "undefined") {
  240. CKEDITOR.instances[key].setData(value);
  241. CKEDITOR.instances[key].focus();
  242. } else {
  243. $("#" + key).html(value);
  244. $("#" + key).focus();
  245. }
  246. });
  247. }
  248. console.log("ajax_autocompleter new value selected, we trigger change also on original component so on field #search_'.$htmlname.'");
  249. $("#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.
  250. }
  251. ,delay: 500
  252. }).data("'.$dataforrenderITem.'")._renderItem = function( ul, item ) {
  253. return $("<li>")
  254. .data( "'.$dataforitem.'", item ) // jQuery UI > 1.10.0
  255. .append( \'<a><span class="tag">\' + item.label + "</span></a>" )
  256. .appendTo(ul);
  257. };
  258. });';
  259. $script .= '</script>';
  260. return $script;
  261. }
  262. /**
  263. * 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).
  264. * The Ajax page can also returns several values (json format) to fill several input fields.
  265. * The HTML field must be an input text with id=$htmlname.
  266. * This use the jQuery "autocomplete" function.
  267. *
  268. * @param string $htmlname HTML name of input field
  269. * @param array $fields Array of key of fields to autocomplete
  270. * @param string $url URL for ajax request : /chemin/fichier.php
  271. * @param string $option More parameters on URL request
  272. * @param int $minLength Minimum number of chars to trigger that Ajax search
  273. * @param int $autoselect Automatic selection if just one value
  274. * @return string Script
  275. */
  276. function ajax_multiautocompleter($htmlname, $fields, $url, $option = '', $minLength = 2, $autoselect = 0)
  277. {
  278. $script = '<!-- Autocomplete -->'."\n";
  279. $script .= '<script>';
  280. $script .= 'jQuery(document).ready(function() {
  281. var fields = '.json_encode($fields).';
  282. var nboffields = fields.length;
  283. var autoselect = '.$autoselect.';
  284. //alert(fields + " " + nboffields);
  285. jQuery("input#'.$htmlname.'").autocomplete({
  286. dataType: "json",
  287. minLength: '.$minLength.',
  288. source: function( request, response ) {
  289. jQuery.getJSON( "'.$url.($option ? '?'.$option : '').'", { '.$htmlname.': request.term }, function(data){
  290. response( jQuery.map( data, function( item ) {
  291. if (autoselect == 1 && data.length == 1) {
  292. jQuery("#'.$htmlname.'").val(item.value);
  293. // TODO move this to specific request
  294. if (item.states) {
  295. jQuery("#state_id").html(item.states);
  296. }
  297. for (i=0;i<nboffields;i++) {
  298. if (item[fields[i]]) { // If defined
  299. //alert(item[fields[i]]);
  300. jQuery("#" + fields[i]).val(item[fields[i]]);
  301. }
  302. }
  303. }
  304. return item
  305. }));
  306. });
  307. },
  308. select: function( event, ui ) {
  309. needtotrigger = "";
  310. for (i=0;i<nboffields;i++) {
  311. //alert(fields[i] + " = " + ui.item[fields[i]]);
  312. if (fields[i]=="selectcountry_id")
  313. {
  314. if (ui.item[fields[i]] > 0) // Do not erase country 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]]);
  320. if (oldvalue != newvalue) // To force select2 to refresh visible content
  321. {
  322. needtotrigger="#" + fields[i];
  323. }
  324. // If we set new country and new state, we need to set a new list of state to allow change
  325. if (ui.item.states && ui.item["state_id"] != jQuery("#state_id").value) {
  326. jQuery("#state_id").html(ui.item.states);
  327. }
  328. }
  329. }
  330. else if (fields[i]=="state_id" || fields[i]=="state_id")
  331. {
  332. if (ui.item[fields[i]] > 0) // Do not erase state if unknown
  333. {
  334. oldvalue=jQuery("#" + fields[i]).val();
  335. newvalue=ui.item[fields[i]];
  336. //alert(oldvalue+" "+newvalue);
  337. jQuery("#" + fields[i]).val(ui.item[fields[i]]); // This may fails if not correct country
  338. if (oldvalue != newvalue) // To force select2 to refresh visible content
  339. {
  340. needtotrigger="#" + fields[i];
  341. }
  342. }
  343. }
  344. else if (ui.item[fields[i]]) { // If defined
  345. oldvalue=jQuery("#" + fields[i]).val();
  346. newvalue=ui.item[fields[i]];
  347. //alert(oldvalue+" "+newvalue);
  348. jQuery("#" + fields[i]).val(ui.item[fields[i]]);
  349. if (oldvalue != newvalue) // To force select2 to refresh visible content
  350. {
  351. needtotrigger="#" + fields[i];
  352. }
  353. }
  354. if (needtotrigger != "") // To force select2 to refresh visible content
  355. {
  356. // 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
  357. // This is required for example when changing zip with autocomplete that change the country
  358. jQuery(needtotrigger).delay(500).queue(function() {
  359. jQuery(this).trigger("change");
  360. });
  361. }
  362. }
  363. }
  364. });
  365. });';
  366. $script .= '</script>';
  367. return $script;
  368. }
  369. /**
  370. * Show an ajax dialog
  371. *
  372. * @param string $title Title of dialog box
  373. * @param string $message Message of dialog box
  374. * @param int $w Width of dialog box
  375. * @param int $h height of dialog box
  376. * @return string
  377. */
  378. function ajax_dialog($title, $message, $w = 350, $h = 150)
  379. {
  380. global $langs;
  381. $newtitle = dol_textishtml($title) ? dol_string_nohtmltag($title, 1) : $title;
  382. $msg = '<div id="dialog-info" title="'.dol_escape_htmltag($newtitle).'">';
  383. $msg .= $message;
  384. $msg .= '</div>'."\n";
  385. $msg .= '<script>
  386. jQuery(function() {
  387. jQuery("#dialog-info").dialog({
  388. resizable: false,
  389. height:'.$h.',
  390. width:'.$w.',
  391. modal: true,
  392. buttons: {
  393. Ok: function() {
  394. jQuery(this).dialog(\'close\');
  395. }
  396. }
  397. });
  398. });
  399. </script>';
  400. $msg .= "\n";
  401. return $msg;
  402. }
  403. /**
  404. * Convert a html select field into an ajax combobox.
  405. * Use ajax_combobox() only for small combo list! If not, use instead ajax_autocompleter().
  406. * 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.
  407. *
  408. * @param string $htmlname Name of html select field ('myid' or '.myclass')
  409. * @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')))
  410. * @param int $minLengthToAutocomplete Minimum length of input string to start autocomplete
  411. * @param int $forcefocus Force focus on field
  412. * @param string $widthTypeOfAutocomplete 'resolve' or 'off'
  413. * @param string $idforemptyvalue '-1'
  414. * @param string $morecss More css
  415. * @return string Return html string to convert a select field into a combo, or '' if feature has been disabled for some reason.
  416. * @see selectArrayAjax() of html.form.class
  417. */
  418. function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = 0, $forcefocus = 0, $widthTypeOfAutocomplete = 'resolve', $idforemptyvalue = '-1', $morecss = '')
  419. {
  420. global $conf;
  421. // select2 can be disabled for smartphones
  422. if (!empty($conf->browser->layout) && $conf->browser->layout == 'phone' && getDolGlobalString('MAIN_DISALLOW_SELECT2_WITH_SMARTPHONE')) {
  423. return '';
  424. }
  425. if (getDolGlobalString('MAIN_DISABLE_AJAX_COMBOX')) {
  426. return '';
  427. }
  428. if (empty($conf->use_javascript_ajax)) {
  429. return '';
  430. }
  431. if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  432. return '';
  433. }
  434. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  435. return '';
  436. }
  437. if (empty($minLengthToAutocomplete)) {
  438. $minLengthToAutocomplete = 0;
  439. }
  440. $moreselect2theme = ($morecss ? dol_escape_js(' '.$morecss) : '');
  441. $moreselect2theme = preg_replace('/widthcentpercentminus[^\s]*/', '', $moreselect2theme);
  442. $tmpplugin = 'select2';
  443. $msg = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id = '.$htmlname.' -->
  444. <script>
  445. $(document).ready(function () {
  446. $(\''.(preg_match('/^\./', $htmlname) ? $htmlname : '#'.$htmlname).'\').'.$tmpplugin.'({
  447. dir: \'ltr\',';
  448. if (preg_match('/onrightofpage/', $morecss)) { // when $morecss contains 'onrightofpage', the select2 component must also be inside a parent with class="parentonrightofpage"
  449. $msg .= ' dropdownAutoWidth: true, dropdownParent: $(\'#'.$htmlname.'\').parent(), '."\n";
  450. }
  451. $msg .= ' width: \''.dol_escape_js($widthTypeOfAutocomplete).'\', /* off or resolve */
  452. minimumInputLength: '.((int) $minLengthToAutocomplete).',
  453. language: select2arrayoflanguage,
  454. matcher: function (params, data) {
  455. if ($.trim(params.term) === "") {
  456. return data;
  457. }
  458. keywords = (params.term).split(" ");
  459. for (var i = 0; i < keywords.length; i++) {
  460. if (((data.text).toUpperCase()).indexOf((keywords[i]).toUpperCase()) == -1) {
  461. return null;
  462. }
  463. }
  464. return data;
  465. },
  466. theme: \'default'.$moreselect2theme.'\', /* to add css on generated html components */
  467. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  468. selectionCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  469. dropdownCssClass: \'ui-dialog\',
  470. templateResult: function (data, container) { /* Format visible output into combo list */
  471. /* Code to add class of origin OPTION propagated to the new select2 <li> tag */
  472. if (data.element) { $(container).addClass($(data.element).attr("class")); }
  473. //console.log("data html is "+$(data.element).attr("data-html"));
  474. if (data.id == '.((int) $idforemptyvalue).' && $(data.element).attr("data-html") == undefined) {
  475. return \'&nbsp;\';
  476. }
  477. if ($(data.element).attr("data-html") != undefined) {
  478. /* If property html set, we decode html entities and use this. */
  479. /* Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, \'\', 0, 1) when building the select option. */
  480. return htmlEntityDecodeJs($(data.element).attr("data-html"));
  481. }
  482. return data.text;
  483. },
  484. templateSelection: function (selection) { /* Format visible output of selected value */
  485. if (selection.id == '.((int) $idforemptyvalue).') return \'<span class="placeholder">\'+selection.text+\'</span>\';
  486. return selection.text;
  487. },
  488. escapeMarkup: function(markup) {
  489. return markup;
  490. }
  491. })';
  492. if ($forcefocus) {
  493. $msg .= '.select2(\'focus\')';
  494. }
  495. $msg .= ';'."\n";
  496. $msg .= '});'."\n";
  497. $msg .= "</script>\n";
  498. $msg .= ajax_event($htmlname, $events);
  499. return $msg;
  500. }
  501. /**
  502. * Add event management script.
  503. *
  504. * @param string $htmlname Name of html select field ('myid' or '.myclass')
  505. * @param array $events Add some Ajax events option on change of $htmlname component to call ajax to autofill a HTML element (select#htmlname and #inputautocompletehtmlname)
  506. * Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
  507. * @return string Return JS string to manage event
  508. */
  509. function ajax_event($htmlname, $events)
  510. {
  511. $out = '';
  512. if (is_array($events) && count($events)) { // If an array of js events to do were provided.
  513. $out = '<!-- JS code to manage event for id = ' . $htmlname . ' -->
  514. <script>
  515. $(document).ready(function () {
  516. jQuery("#'.$htmlname.'").change(function () {
  517. var obj = '.json_encode($events) . ';
  518. $.each(obj, function(key,values) {
  519. if (values.method.length) {
  520. runJsCodeForEvent'.$htmlname.'(values);
  521. }
  522. });
  523. });
  524. function runJsCodeForEvent'.$htmlname.'(obj) {
  525. var id = $("#'.$htmlname.'").val();
  526. var method = obj.method;
  527. var url = obj.url;
  528. var htmlname = obj.htmlname;
  529. var showempty = obj.showempty;
  530. console.log("Run runJsCodeForEvent-'.$htmlname.' from ajax_combobox id="+id+" method="+method+" showempty="+showempty+" url="+url+" htmlname="+htmlname);
  531. $.getJSON(url,
  532. {
  533. action: method,
  534. id: id,
  535. htmlname: htmlname,
  536. showempty: showempty
  537. },
  538. function(response) {
  539. $.each(obj.params, function(key,action) {
  540. if (key.length) {
  541. var num = response.num;
  542. if (num > 0) {
  543. $("#" + key).removeAttr(action);
  544. } else {
  545. $("#" + key).attr(action, action);
  546. }
  547. }
  548. });
  549. $("select#" + htmlname).html(response.value);
  550. if (response.num) {
  551. var selecthtml_str = response.value;
  552. var selecthtml_dom=$.parseHTML(selecthtml_str);
  553. if (typeof(selecthtml_dom[0][0]) !== \'undefined\') {
  554. $("#inputautocomplete"+htmlname).val(selecthtml_dom[0][0].innerHTML);
  555. }
  556. } else {
  557. $("#inputautocomplete"+htmlname).val("");
  558. }
  559. $("select#" + htmlname).change(); /* Trigger event change */
  560. }
  561. );
  562. }
  563. });
  564. </script>';
  565. }
  566. return $out;
  567. }
  568. /**
  569. * On/off button for constant
  570. *
  571. * @param string $code Name of constant
  572. * @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'))
  573. * @param int $entity Entity. Current entity is used if null.
  574. * @param int $revertonoff 1=Revert on/off
  575. * @param int $strict Use only "disabled" with delConstant and "enabled" with setConstant
  576. * @param int $forcereload Force to reload page if we click/change value (this is supported only when there is no 'alert' option in input)
  577. * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No left margin.
  578. * @param int $forcenoajax 1 = Force to use a ahref link instead of ajax code.
  579. * @param int $setzeroinsteadofdel 1 = Set constantto '0' instead of deleting it
  580. * @param string $suffix Suffix to use on the name of the switch_on picto. Example: '', '_red'
  581. * @param string $mode Add parameter &mode= to the href link (Used for href link)
  582. * @param string $morecss More CSS
  583. * @return string
  584. */
  585. function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0, $setzeroinsteadofdel = 0, $suffix = '', $mode = '', $morecss = 'inline-block')
  586. {
  587. global $conf, $langs, $user;
  588. $entity = ((isset($entity) && is_numeric($entity) && $entity >= 0) ? $entity : $conf->entity);
  589. if (!isset($input)) {
  590. $input = array();
  591. }
  592. if (empty($conf->use_javascript_ajax) || $forcenoajax) {
  593. if (empty($conf->global->$code)) {
  594. $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>';
  595. } else {
  596. $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>';
  597. }
  598. } else {
  599. $out = "\n<!-- Ajax code to switch constant ".$code." -->".'
  600. <script>
  601. $(document).ready(function() {
  602. var input = '.json_encode($input).';
  603. var url = \''.DOL_URL_ROOT.'/core/ajax/constantonoff.php\';
  604. var code = \''.dol_escape_js($code).'\';
  605. var entity = \''.dol_escape_js($entity).'\';
  606. var strict = \''.dol_escape_js($strict).'\';
  607. var userid = \''.dol_escape_js($user->id).'\';
  608. var yesButton = \''.dol_escape_js($langs->transnoentities("Yes")).'\';
  609. var noButton = \''.dol_escape_js($langs->transnoentities("No")).'\';
  610. var token = \''.currentToken().'\';
  611. // Set constant
  612. $("#set_" + code).click(function() {
  613. if (input.alert && input.alert.set) {
  614. if (input.alert.set.yesButton) yesButton = input.alert.set.yesButton;
  615. if (input.alert.set.noButton) noButton = input.alert.set.noButton;
  616. confirmConstantAction("set", url, code, input, input.alert.set, entity, yesButton, noButton, strict, userid, token);
  617. } else {
  618. setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);
  619. }
  620. });
  621. // Del constant
  622. $("#del_" + code).click(function() {
  623. if (input.alert && input.alert.del) {
  624. if (input.alert.del.yesButton) yesButton = input.alert.del.yesButton;
  625. if (input.alert.del.noButton) noButton = input.alert.del.noButton;
  626. confirmConstantAction("del", url, code, input, input.alert.del, entity, yesButton, noButton, strict, userid, token);
  627. } else {';
  628. if (empty($setzeroinsteadofdel)) {
  629. $out .=' delConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token);';
  630. } else {
  631. $out .=' setConstant(url, code, input, entity, 0, '.((int) $forcereload).', userid, token, 0);';
  632. }
  633. $out .= ' }
  634. });
  635. });
  636. </script>'."\n";
  637. $out .= '<div id="confirm_'.$code.'" title="" style="display: none;"></div>';
  638. $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>';
  639. $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>';
  640. $out .= "\n";
  641. }
  642. return $out;
  643. }
  644. /**
  645. * On/off button to change a property status of an object
  646. * This uses the ajax service objectonoff.php (May be called when MAIN_DIRECT_STATUS_UPDATE is set for some pages)
  647. *
  648. * @param Object $object Object to set
  649. * @param string $code Name of property in object : 'status' or 'status_buy' for product by example
  650. * @param string $field Name of database field : 'tosell' or 'tobuy' for product by example
  651. * @param string $text_on Text if on ('Text' or 'Text:Picto on:Css picto on')
  652. * @param string $text_off Text if off ('Text' or 'Text:Picto off:Css picto off')
  653. * @param array $input Array of type->list of CSS element to switch. Example: array('disabled'=>array(0=>'cssid'))
  654. * @param string $morecss More CSS
  655. * @param string $htmlname Name of HTML component. Keep '' or use a different value if you need to use this component several time on the same page for the same field.
  656. * @param int $forcenojs Force the component to work as link post (without javascript) instead of ajax call
  657. * @return string html for button on/off
  658. */
  659. function ajax_object_onoff($object, $code, $field, $text_on, $text_off, $input = array(), $morecss = '', $htmlname = '', $forcenojs = 0)
  660. {
  661. global $conf, $langs;
  662. if (empty($htmlname)) {
  663. $htmlname = $code;
  664. }
  665. //var_dump($object->module); var_dump($object->element);
  666. $out = '';
  667. if (!empty($conf->use_javascript_ajax)) {
  668. $out .= '<script>
  669. $(function() {
  670. var input = '.json_encode($input).';
  671. // Set constant
  672. $("#set_'.$htmlname.'_'.$object->id.'").click(function() {
  673. console.log("Click managed by ajax_object_onoff");
  674. $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
  675. action: \'set\',
  676. field: \''.dol_escape_js($field).'\',
  677. value: \'1\',
  678. element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
  679. id: \''.((int) $object->id).'\',
  680. token: \''.currentToken().'\'
  681. },
  682. function() {
  683. $("#set_'.$htmlname.'_'.$object->id.'").hide();
  684. $("#del_'.$htmlname.'_'.$object->id.'").show();
  685. // Enable another element
  686. if (input.disabled && input.disabled.length > 0) {
  687. $.each(input.disabled, function(key,value) {
  688. $("#" + value).removeAttr("disabled");
  689. if ($("#" + value).hasClass("butActionRefused") == true) {
  690. $("#" + value).removeClass("butActionRefused");
  691. $("#" + value).addClass("butAction");
  692. }
  693. });
  694. // Show another element
  695. } else if (input.showhide && input.showhide.length > 0) {
  696. $.each(input.showhide, function(key,value) {
  697. $("#" + value).show();
  698. });
  699. }
  700. });
  701. });
  702. // Del constant
  703. $("#del_'.$htmlname.'_'.$object->id.'").click(function() {
  704. console.log("Click managed by ajax_object_onoff");
  705. $.get( "'.DOL_URL_ROOT.'/core/ajax/objectonoff.php", {
  706. action: \'set\',
  707. field: \''.dol_escape_js($field).'\',
  708. value: \'0\',
  709. element: \''.dol_escape_js((empty($object->module) || $object->module == $object->element) ? $object->element : $object->element.'@'.$object->module).'\',
  710. id: \''.((int) $object->id).'\',
  711. token: \''.currentToken().'\'
  712. },
  713. function() {
  714. $("#del_'.$htmlname.'_'.$object->id.'").hide();
  715. $("#set_'.$htmlname.'_'.$object->id.'").show();
  716. // Disable another element
  717. if (input.disabled && input.disabled.length > 0) {
  718. $.each(input.disabled, function(key,value) {
  719. $("#" + value).prop("disabled", true);
  720. if ($("#" + value).hasClass("butAction") == true) {
  721. $("#" + value).removeClass("butAction");
  722. $("#" + value).addClass("butActionRefused");
  723. }
  724. });
  725. // Hide another element
  726. } else if (input.showhide && input.showhide.length > 0) {
  727. $.each(input.showhide, function(key,value) {
  728. $("#" + value).hide();
  729. });
  730. }
  731. });
  732. });
  733. });
  734. </script>';
  735. }
  736. $switchon = 'switch_on';
  737. $switchoff = 'switch_off';
  738. $cssswitchon = '';
  739. $cssswitchoff = '';
  740. $tmparray = explode(':', $text_on);
  741. if (!empty($tmparray[1])) {
  742. $text_on = $tmparray[0];
  743. $switchon = $tmparray[1];
  744. if (!empty($tmparray[2])) {
  745. $cssswitchon = $tmparray[2];
  746. }
  747. }
  748. $tmparray = explode(':', $text_off);
  749. if (!empty($tmparray[1])) {
  750. $text_off = $tmparray[0];
  751. $switchoff = $tmparray[1];
  752. if (!empty($tmparray[2])) {
  753. $cssswitchoff = $tmparray[2];
  754. }
  755. }
  756. if (empty($conf->use_javascript_ajax) || $forcenojs) {
  757. $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>';
  758. $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>';
  759. } else {
  760. $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>';
  761. $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>';
  762. }
  763. return $out;
  764. }