forms-json-utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // Copyright (C) 2010-2016 Combodo SARL
  2. //
  3. // This file is part of iTop.
  4. //
  5. // iTop is free software; you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // iTop is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  17. // ID of the (hidden) form field used to store the JSON representation of the
  18. // object being edited in this page
  19. var sJsonFieldId = 'json_object';
  20. // The memory representation of the object
  21. var oObj = {};
  22. // Mapping between the fields of the form and the attribute of the current object
  23. // If aFieldsMap[2] contains 'foo' it means that oObj.foo corresponds to the field
  24. // of Id 'att_2' in the form
  25. var aFieldsMap = new Array;
  26. window.bInSubmit = false; // For handling form cancellation via OnBeforeUnload events
  27. // Update the whole object from the form and also update its
  28. // JSON (serialized) representation in the (hidden) field
  29. function UpdateObjectFromForm(aFieldsMap, oObj)
  30. {
  31. for(i=0; i<aFieldsMap.length; i++)
  32. {
  33. var oElement = document.getElementById('att_'+i);
  34. var sFieldName = aFieldsMap[i];
  35. oObj['m_aCurrValues'][sFieldName] = oElement.value;
  36. sJSON = JSON.stringify(oObj);
  37. var oJSON = document.getElementById(sJsonFieldId);
  38. oJSON.value = sJSON;
  39. }
  40. return oObj;
  41. }
  42. // Update the specified field from the current object
  43. function UpdateFieldFromObject(idField, aFieldsMap, oObj)
  44. {
  45. var oElement = document.getElementById('att_'+idField);
  46. oElement.value = oObj['m_aCurrValues'][aFieldsMap[idField]];
  47. }
  48. // Update all the fields of the Form from the current object
  49. function UpdateFormFromObject(aFieldsMap, oObj)
  50. {
  51. for(i=0; i<aFieldsMap.length; i++)
  52. {
  53. UpdateFieldFromForm(i, aFieldsMap, oObj);
  54. }
  55. }
  56. // This function is meant to be called from the AJAX page
  57. // It reloads the object (oObj) from the JSON representation
  58. // and also updates the form field that contains the JSON
  59. // representation of the object
  60. function ReloadObjectFromServer(sJSON)
  61. {
  62. //console.log('JSON value:', sJSON);
  63. var oJSON = document.getElementById(sJsonFieldId);
  64. oJSON.value = sJSON;
  65. oObj = JSON.parse( '(' + sJSON + ')' );
  66. return oObj;
  67. }
  68. function GoToStep(iCurrentStep, iNextStep)
  69. {
  70. var oCurrentStep = document.getElementById('wizStep'+iCurrentStep);
  71. if (iNextStep > iCurrentStep)
  72. {
  73. // Check the values when moving forward
  74. if (CheckFields('wizStep'+iCurrentStep, true))
  75. {
  76. oCurrentStep.style.display = 'none';
  77. ActivateStep(iNextStep);
  78. }
  79. }
  80. else
  81. {
  82. oCurrentStep.style.display = 'none';
  83. ActivateStep(iNextStep);
  84. }
  85. }
  86. function ActivateStep(iTargetStep)
  87. {
  88. UpdateObjectFromForm(aFieldsMap, oObj);
  89. var oNextStep = document.getElementById('wizStep'+(iTargetStep));
  90. window.location.href='#step'+iTargetStep;
  91. // If a handler for entering this step exists, call it
  92. if (typeof(this['OnEnterStep'+iTargetStep]) == 'function')
  93. {
  94. eval( 'OnEnterStep'+iTargetStep+'();');
  95. }
  96. oNextStep.style.display = '';
  97. G_iCurrentStep = iTargetStep;
  98. //$('#wizStep'+(iTargetStep)).block({ message: null });
  99. }
  100. function OnUnload(sTransactionId, sObjClass, iObjKey, sToken)
  101. {
  102. if (!window.bInSubmit)
  103. {
  104. // If it's not a submit, then it's a "cancel" (Pressing the Cancel button, closing the window, using the back button...)
  105. // IMPORTANT: the ajax request MUST BE synchronous to be executed in this context
  106. $.ajax({
  107. url: GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
  108. async: false,
  109. method: 'POST',
  110. data: {operation: 'on_form_cancel', transaction_id: sTransactionId, obj_class: sObjClass, obj_key: iObjKey, token: sToken }
  111. });
  112. }
  113. }
  114. function OnSubmit(sFormId)
  115. {
  116. window.bInSubmit=true; // This is a submit, make sure that when the page gets unloaded we don't cancel the action
  117. var bResult = CheckFields(sFormId, true);
  118. if (!bResult)
  119. {
  120. window.bInSubmit = false; // Submit is/will be canceled
  121. }
  122. return bResult;
  123. }
  124. // Store the result of the form validation... there may be several forms per page, beware
  125. var oFormErrors = { err_form0: 0 };
  126. function CheckFields(sFormId, bDisplayAlert)
  127. {
  128. $('#'+sFormId+' :submit').attr('disable', 'disabled');
  129. $('#'+sFormId+' :button[type=submit]').attr('disable', 'disabled');
  130. firstErrorId = '';
  131. // The two 'fields' below will be updated when the 'validate' event is processed
  132. oFormErrors['err_'+sFormId] = 0; // Number of errors encountered when validating the form
  133. oFormErrors['input_'+sFormId] = null; // First 'input' with an error, to set the focus to it
  134. $('#'+sFormId+' :input').each( function()
  135. {
  136. validateEventResult = $(this).trigger('validate', sFormId);
  137. }
  138. );
  139. if(oFormErrors['err_'+sFormId] > 0)
  140. {
  141. if (bDisplayAlert)
  142. {
  143. alert(Dict.S('UI:FillAllMandatoryFields'));
  144. }
  145. $('#'+sFormId+' :submit').attr('disable', '');
  146. $('#'+sFormId+' :button[type=submit]').attr('disable', '');
  147. if (oFormErrors['input_'+sFormId] != null)
  148. {
  149. $('#'+oFormErrors['input_'+sFormId]).focus();
  150. }
  151. }
  152. return (oFormErrors['err_'+sFormId] == 0); // If no error, submit the form
  153. }
  154. function ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain)
  155. {
  156. if (bValid)
  157. {
  158. // Visual feedback - none when it's Ok
  159. $('#v_'+sFieldId).html(''); //<img src="../images/validation_ok.png" />');
  160. }
  161. else
  162. {
  163. // Report the error...
  164. oFormErrors['err_'+sFormId]++;
  165. if (oFormErrors['input_'+sFormId] == null)
  166. {
  167. // Let's remember the first input with an error, so that we can put back the focus on it later
  168. oFormErrors['input_'+sFormId] = sFieldId;
  169. }
  170. // Visual feedback
  171. $('#v_'+sFieldId).html('<img src="../images/validation_error.png" style="vertical-align:middle" data-tooltip="'+sExplain+'"/>');
  172. $('#v_'+sFieldId).tooltip({
  173. items: 'span',
  174. tooltipClass: 'form_field_error',
  175. content: function() {
  176. return $(this).find('img').attr('data-tooltip'); // As opposed to the default 'content' handler, do not escape the contents of 'title'
  177. }
  178. });
  179. }
  180. }
  181. function ValidateField(sFieldId, sPattern, bMandatory, sFormId, nullValue, originalValue)
  182. {
  183. var bValid = true;
  184. var sExplain = '';
  185. if ($('#'+sFieldId).attr('disabled'))
  186. {
  187. bValid = true; // disabled fields are not checked
  188. }
  189. else
  190. {
  191. var currentVal = $('#'+sFieldId).val();
  192. if (currentVal == '$$NULL$$') // Convention to indicate a non-valid value since it may have to be passed as text
  193. {
  194. bValid = false;
  195. }
  196. else if (bMandatory && (currentVal == nullValue))
  197. {
  198. bValid = false;
  199. sExplain = Dict.S('UI:ValueMustBeSet');
  200. }
  201. else if ((originalValue != undefined) && (currentVal == originalValue))
  202. {
  203. bValid = false;
  204. if (originalValue == nullValue)
  205. {
  206. sExplain = Dict.S('UI:ValueMustBeSet');
  207. }
  208. else
  209. {
  210. sExplain = Dict.S('UI:ValueMustBeChanged');
  211. }
  212. }
  213. else if (currentVal == nullValue)
  214. {
  215. // An empty field is Ok...
  216. bValid = true;
  217. }
  218. else if (sPattern != '')
  219. {
  220. re = new RegExp(sPattern);
  221. //console.log('Validating field: '+sFieldId + ' current value: '+currentVal + ' pattern: '+sPattern );
  222. bValid = re.test(currentVal);
  223. sExplain = Dict.S('UI:ValueInvalidFormat');
  224. }
  225. }
  226. ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain);
  227. //console.log('Form: '+sFormId+' Validating field: '+sFieldId + ' current value: '+currentVal+' pattern: '+sPattern+' result: '+bValid );
  228. return true; // Do not stop propagation ??
  229. }
  230. function ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue)
  231. {
  232. var bValid;
  233. var sTextContent;
  234. if ($('#'+sFieldId).attr('disabled'))
  235. {
  236. bValid = true; // disabled fields are not checked
  237. }
  238. else
  239. {
  240. // Get the contents without the tags
  241. var oFormattedContents = $("#cke_"+sFieldId+" iframe");
  242. if (oFormattedContents.length == 0)
  243. {
  244. var oSourceContents = $("#cke_"+sFieldId+" textarea.cke_source");
  245. sTextContent = oSourceContents.val();
  246. }
  247. else
  248. {
  249. sTextContent = oFormattedContents.contents().find("body").text();
  250. if (sTextContent == '')
  251. {
  252. // No plain text, maybe there is just an image...
  253. var oImg = oFormattedContents.contents().find("body img");
  254. if (oImg.length != 0)
  255. {
  256. sTextContent = 'image';
  257. }
  258. }
  259. }
  260. if (bMandatory && (sTextContent == ''))
  261. {
  262. bValid = false;
  263. }
  264. else
  265. {
  266. bValid = true;
  267. }
  268. }
  269. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  270. setTimeout(function(){ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue);}, 500);
  271. }
  272. /*
  273. function UpdateDependentFields(aFieldNames)
  274. {
  275. //console.log('UpdateDependentFields:');
  276. //console.log(aFieldNames);
  277. index = 0;
  278. oWizardHelper.ResetQuery();
  279. oWizardHelper.UpdateWizard();
  280. while(index < aFieldNames.length )
  281. {
  282. sAttCode = aFieldNames[index];
  283. sFieldId = oWizardHelper.GetFieldId(sAttCode);
  284. $('#v_'+sFieldId).html('<img src="../images/indicator.gif" />');
  285. oWizardHelper.RequestAllowedValues(sAttCode);
  286. index++;
  287. }
  288. oWizardHelper.AjaxQueryServer();
  289. }
  290. */
  291. function ResetPwd(id)
  292. {
  293. // Reset the values of the password fields
  294. $('#'+id).val('*****');
  295. $('#'+id+'_confirm').val('*****');
  296. // And reset the flag, to tell it that the password remains unchanged
  297. $('#'+id+'_changed').val(0);
  298. // Visual feedback, None when it's Ok
  299. $('#v_'+id).html('');
  300. }
  301. // Called whenever the content of a one way encrypted password changes
  302. function PasswordFieldChanged(id)
  303. {
  304. // Set the flag, to tell that the password changed
  305. $('#'+id+'_changed').val(1);
  306. }
  307. // Special validation function for one way encrypted password fields
  308. function ValidatePasswordField(id, sFormId)
  309. {
  310. var bChanged = $('#'+id+'_changed').val();
  311. if (bChanged)
  312. {
  313. if ($('#'+id).val() != $('#'+id+'_confirm').val())
  314. {
  315. oFormErrors['err_'+sFormId]++;
  316. if (oFormErrors['input_'+sFormId] == null)
  317. {
  318. // Let's remember the first input with an error, so that we can put back the focus on it later
  319. oFormErrors['input_'+sFormId] = id;
  320. }
  321. // Visual feedback
  322. $('#v_'+id).html('<img src="../images/validation_error.png" style="vertical-align:middle"/>');
  323. return false;
  324. }
  325. }
  326. $('#v_'+id).html(''); //<img src="../images/validation_ok.png" />');
  327. return true;
  328. }
  329. //Special validation function for case log fields, taking into account the history
  330. // to determine if the field is empty or not
  331. function ValidateCaseLogField(sFieldId, bMandatory, sFormId)
  332. {
  333. bValid = true;
  334. if ($('#'+sFieldId).attr('disabled'))
  335. {
  336. bValid = true; // disabled fields are not checked
  337. }
  338. else if (!bMandatory)
  339. {
  340. bValid = true;
  341. }
  342. else
  343. {
  344. if (bMandatory)
  345. {
  346. var count = $('#'+sFieldId+'_count').val();
  347. if ( (count == 0) && ($('#'+sFieldId).val() == '') )
  348. {
  349. // No previous entry and no content typed
  350. bValid = false;
  351. }
  352. }
  353. }
  354. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  355. return bValid;
  356. }
  357. // Validate the inputs depending on the current setting
  358. function ValidateRedundancySettings(sFieldId, sFormId)
  359. {
  360. var bValid = true;
  361. var sExplain = '';
  362. $('#'+sFieldId+' :input[type="radio"]:checked').parent().find(':input[type="string"]').each(function (){
  363. var sValue = $(this).val().trim();
  364. if (sValue == '')
  365. {
  366. bValid = false;
  367. sExplain = Dict.S('UI:ValueMustBeSet');
  368. }
  369. else
  370. {
  371. // There is something... check if it is a number
  372. re = new RegExp('^[0-9]+$');
  373. bValid = re.test(sValue);
  374. if (bValid)
  375. {
  376. var iValue = parseInt(sValue , 10);
  377. if ($(this).hasClass('redundancy-min-up-percent'))
  378. {
  379. // A percentage
  380. if ((iValue < 0) || (iValue > 100))
  381. {
  382. bValid = false;
  383. }
  384. }
  385. else if ($(this).hasClass('redundancy-min-up-count'))
  386. {
  387. // A count
  388. if (iValue < 0)
  389. {
  390. bValid = false;
  391. }
  392. }
  393. }
  394. if (!bValid)
  395. {
  396. sExplain = Dict.S('UI:ValueInvalidFormat');
  397. }
  398. }
  399. });
  400. ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain);
  401. return bValid;
  402. }
  403. //Special validation function for custom fields
  404. function ValidateCustomFields(sFieldId, sFormId)
  405. {
  406. var oFieldSet = $('#'+sFieldId+'_console_form').console_form_handler('option', 'field_set');
  407. bValid = oFieldSet.triggerHandler('validate');
  408. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  409. return bValid;
  410. }
  411. // Manage a 'duration' field
  412. function UpdateDuration(iId)
  413. {
  414. var iDays = parseInt($('#'+iId+'_d').val(), 10);
  415. var iHours = parseInt($('#'+iId+'_h').val(), 10);
  416. var iMinutes = parseInt($('#'+iId+'_m').val(), 10);
  417. var iSeconds = parseInt($('#'+iId+'_s').val(), 10);
  418. var iDuration = (((iDays*24)+ iHours)*60+ iMinutes)*60 + iSeconds;
  419. $('#'+iId).val(iDuration);
  420. $('#'+iId).trigger('change');
  421. return true;
  422. }
  423. // Called when filling an autocomplete field
  424. function OnAutoComplete(id, event, data, formatted)
  425. {
  426. if (data)
  427. {
  428. // A valid match was found: data[0] => label, data[1] => value
  429. if (data[1] != $('#'+id).val())
  430. {
  431. $('#'+id).val(data[1]);
  432. $('#'+id).trigger('change');
  433. $('#'+id).trigger('extkeychange');
  434. }
  435. }
  436. else
  437. {
  438. if ($('#label_'+id).val() == '')
  439. {
  440. $('#'+id).val(''); // Empty value
  441. }
  442. else
  443. {
  444. $('#'+id).val('$$NULL$$'); // Convention: not a valid value
  445. }
  446. $('#'+id).trigger('change');
  447. }
  448. }