forms-json-utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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)
  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. $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', {operation: 'on_form_cancel', transaction_id: sTransactionId }, function()
  90. {
  91. // Do nothing for now...
  92. });
  93. }
  94. }
  95. function OnSubmit(sFormId)
  96. {
  97. window.bInSubmit=true; // This is a submit, make sure that when the page gets unloaded we don't cancel the action
  98. var bResult = CheckFields(sFormId, true);
  99. if (!bResult)
  100. {
  101. window.bInSubmit = false; // Submit is/will be canceled
  102. }
  103. return bResult;
  104. }
  105. // Store the result of the form validation... there may be several forms per page, beware
  106. var oFormErrors = { err_form0: 0 };
  107. function CheckFields(sFormId, bDisplayAlert)
  108. {
  109. $('#'+sFormId+' :submit').attr('disable', 'disabled');
  110. $('#'+sFormId+' :button[type=submit]').attr('disable', 'disabled');
  111. firstErrorId = '';
  112. // The two 'fields' below will be updated when the 'validate' event is processed
  113. oFormErrors['err_'+sFormId] = 0; // Number of errors encountered when validating the form
  114. oFormErrors['input_'+sFormId] = null; // First 'input' with an error, to set the focus to it
  115. $('#'+sFormId+' :input').each( function()
  116. {
  117. validateEventResult = $(this).trigger('validate', sFormId);
  118. }
  119. );
  120. if(oFormErrors['err_'+sFormId] > 0)
  121. {
  122. if (bDisplayAlert)
  123. {
  124. alert(Dict.S('UI:FillAllMandatoryFields'));
  125. }
  126. $('#'+sFormId+' :submit').attr('disable', '');
  127. $('#'+sFormId+' :button[type=submit]').attr('disable', '');
  128. if (oFormErrors['input_'+sFormId] != null)
  129. {
  130. $('#'+oFormErrors['input_'+sFormId]).focus();
  131. }
  132. }
  133. return (oFormErrors['err_'+sFormId] == 0); // If no error, submit the form
  134. }
  135. function ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain)
  136. {
  137. if (bValid)
  138. {
  139. // Visual feedback - none when it's Ok
  140. $('#v_'+sFieldId).html(''); //<img src="../images/validation_ok.png" />');
  141. }
  142. else
  143. {
  144. // Report the error...
  145. oFormErrors['err_'+sFormId]++;
  146. if (oFormErrors['input_'+sFormId] == null)
  147. {
  148. // Let's remember the first input with an error, so that we can put back the focus on it later
  149. oFormErrors['input_'+sFormId] = sFieldId;
  150. }
  151. // Visual feedback
  152. $('#v_'+sFieldId).html('<img src="../images/validation_error.png" style="vertical-align:middle" data-tooltip="'+sExplain+'"/>');
  153. $('#v_'+sFieldId).tooltip({
  154. items: 'span',
  155. tooltipClass: 'form_field_error',
  156. content: function() {
  157. return $(this).find('img').attr('data-tooltip'); // As opposed to the default 'content' handler, do not escape the contents of 'title'
  158. }
  159. });
  160. }
  161. }
  162. function ValidateField(sFieldId, sPattern, bMandatory, sFormId, nullValue, originalValue)
  163. {
  164. var bValid = true;
  165. var sExplain = '';
  166. if ($('#'+sFieldId).attr('disabled'))
  167. {
  168. bValid = true; // disabled fields are not checked
  169. }
  170. else
  171. {
  172. var currentVal = $('#'+sFieldId).val();
  173. if (currentVal == '$$NULL$$') // Convention to indicate a non-valid value since it may have to be passed as text
  174. {
  175. bValid = false;
  176. }
  177. else if (bMandatory && (currentVal == nullValue))
  178. {
  179. bValid = false;
  180. sExplain = Dict.S('UI:ValueMustBeSet');
  181. }
  182. else if ((originalValue != undefined) && (currentVal == originalValue))
  183. {
  184. bValid = false;
  185. if (originalValue == nullValue)
  186. {
  187. sExplain = Dict.S('UI:ValueMustBeSet');
  188. }
  189. else
  190. {
  191. sExplain = Dict.S('UI:ValueMustBeChanged');
  192. }
  193. }
  194. else if (currentVal == nullValue)
  195. {
  196. // An empty field is Ok...
  197. bValid = true;
  198. }
  199. else if (sPattern != '')
  200. {
  201. re = new RegExp(sPattern);
  202. //console.log('Validating field: '+sFieldId + ' current value: '+currentVal + ' pattern: '+sPattern );
  203. bValid = re.test(currentVal);
  204. sExplain = Dict.S('UI:ValueInvalidFormat');
  205. }
  206. }
  207. ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain);
  208. //console.log('Form: '+sFormId+' Validating field: '+sFieldId + ' current value: '+currentVal+' pattern: '+sPattern+' result: '+bValid );
  209. return true; // Do not stop propagation ??
  210. }
  211. function ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue)
  212. {
  213. var bValid;
  214. var sTextContent;
  215. // Get the contents without the tags
  216. var oFormattedContents = $("#cke_"+sFieldId+" iframe");
  217. if (oFormattedContents.length == 0)
  218. {
  219. var oSourceContents = $("#cke_"+sFieldId+" textarea.cke_source");
  220. sTextContent = oSourceContents.val();
  221. }
  222. else
  223. {
  224. sTextContent = oFormattedContents.contents().find("body").text();
  225. }
  226. if (bMandatory && (sTextContent == ''))
  227. {
  228. bValid = false;
  229. }
  230. else
  231. {
  232. bValid = true;
  233. }
  234. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  235. setTimeout(function(){ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue);}, 500);
  236. }
  237. /*
  238. function UpdateDependentFields(aFieldNames)
  239. {
  240. //console.log('UpdateDependentFields:');
  241. //console.log(aFieldNames);
  242. index = 0;
  243. oWizardHelper.ResetQuery();
  244. oWizardHelper.UpdateWizard();
  245. while(index < aFieldNames.length )
  246. {
  247. sAttCode = aFieldNames[index];
  248. sFieldId = oWizardHelper.GetFieldId(sAttCode);
  249. $('#v_'+sFieldId).html('<img src="../images/indicator.gif" />');
  250. oWizardHelper.RequestAllowedValues(sAttCode);
  251. index++;
  252. }
  253. oWizardHelper.AjaxQueryServer();
  254. }
  255. */
  256. function ResetPwd(id)
  257. {
  258. // Reset the values of the password fields
  259. $('#'+id).val('*****');
  260. $('#'+id+'_confirm').val('*****');
  261. // And reset the flag, to tell it that the password remains unchanged
  262. $('#'+id+'_changed').val(0);
  263. // Visual feedback, None when it's Ok
  264. $('#v_'+id).html('');
  265. }
  266. // Called whenever the content of a one way encrypted password changes
  267. function PasswordFieldChanged(id)
  268. {
  269. // Set the flag, to tell that the password changed
  270. $('#'+id+'_changed').val(1);
  271. }
  272. // Special validation function for one way encrypted password fields
  273. function ValidatePasswordField(id, sFormId)
  274. {
  275. var bChanged = $('#'+id+'_changed').val();
  276. if (bChanged)
  277. {
  278. if ($('#'+id).val() != $('#'+id+'_confirm').val())
  279. {
  280. oFormErrors['err_'+sFormId]++;
  281. if (oFormErrors['input_'+sFormId] == null)
  282. {
  283. // Let's remember the first input with an error, so that we can put back the focus on it later
  284. oFormErrors['input_'+sFormId] = id;
  285. }
  286. // Visual feedback
  287. $('#v_'+id).html('<img src="../images/validation_error.png" style="vertical-align:middle"/>');
  288. return false;
  289. }
  290. }
  291. $('#v_'+id).html(''); //<img src="../images/validation_ok.png" />');
  292. return true;
  293. }
  294. //Special validation function for case log fields, taking into account the history
  295. // to determine if the field is empty or not
  296. function ValidateCaseLogField(sFieldId, bMandatory, sFormId)
  297. {
  298. bValid = true;
  299. if ($('#'+sFieldId).attr('disabled'))
  300. {
  301. bValid = true; // disabled fields are not checked
  302. }
  303. else if (!bMandatory)
  304. {
  305. bValid = true;
  306. }
  307. else
  308. {
  309. if (bMandatory)
  310. {
  311. var count = $('#'+sFieldId+'_count').val();
  312. if ( (count == 0) && ($('#'+sFieldId).val() == '') )
  313. {
  314. // No previous entry and no content typed
  315. bValid = false;
  316. }
  317. }
  318. }
  319. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  320. return bValid;
  321. }
  322. // Validate the inputs depending on the current setting
  323. function ValidateRedundancySettings(sFieldId, sFormId)
  324. {
  325. var bValid = true;
  326. var sExplain = '';
  327. $('#'+sFieldId+' :input[type="radio"]:checked').parent().find(':input[type="string"]').each(function (){
  328. var sValue = $(this).val().trim();
  329. if (sValue == '')
  330. {
  331. bValid = false;
  332. sExplain = Dict.S('UI:ValueMustBeSet');
  333. }
  334. else
  335. {
  336. // There is something... check if it is a number
  337. re = new RegExp('^[0-9]+$');
  338. bValid = re.test(sValue);
  339. if (bValid)
  340. {
  341. var iValue = parseInt(sValue , 10);
  342. if ($(this).hasClass('redundancy-min-up-percent'))
  343. {
  344. // A percentage
  345. if ((iValue < 0) || (iValue > 100))
  346. {
  347. bValid = false;
  348. }
  349. }
  350. else if ($(this).hasClass('redundancy-min-up-count'))
  351. {
  352. // A count
  353. if (iValue < 0)
  354. {
  355. bValid = false;
  356. }
  357. }
  358. }
  359. if (!bValid)
  360. {
  361. sExplain = Dict.S('UI:ValueInvalidFormat');
  362. }
  363. }
  364. });
  365. ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain);
  366. return bValid;
  367. }
  368. // Manage a 'duration' field
  369. function UpdateDuration(iId)
  370. {
  371. var iDays = parseInt($('#'+iId+'_d').val(), 10);
  372. var iHours = parseInt($('#'+iId+'_h').val(), 10);
  373. var iMinutes = parseInt($('#'+iId+'_m').val(), 10);
  374. var iSeconds = parseInt($('#'+iId+'_s').val(), 10);
  375. var iDuration = (((iDays*24)+ iHours)*60+ iMinutes)*60 + iSeconds;
  376. $('#'+iId).val(iDuration);
  377. $('#'+iId).trigger('change');
  378. return true;
  379. }
  380. // Called when filling an autocomplete field
  381. function OnAutoComplete(id, event, data, formatted)
  382. {
  383. if (data)
  384. {
  385. // A valid match was found: data[0] => label, data[1] => value
  386. if (data[1] != $('#'+id).val())
  387. {
  388. $('#'+id).val(data[1]);
  389. $('#'+id).trigger('change');
  390. $('#'+id).trigger('extkeychange');
  391. }
  392. }
  393. else
  394. {
  395. if ($('#label_'+id).val() == '')
  396. {
  397. $('#'+id).val(''); // Empty value
  398. }
  399. else
  400. {
  401. $('#'+id).val('$$NULL$$'); // Convention: not a valid value
  402. }
  403. $('#'+id).trigger('change');
  404. }
  405. }