forms-json-utils.js 12 KB

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