forms-json-utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. // Get the contents without the tags
  219. var oFormattedContents = $("#cke_"+sFieldId+" iframe");
  220. if (oFormattedContents.length == 0)
  221. {
  222. var oSourceContents = $("#cke_"+sFieldId+" textarea.cke_source");
  223. sTextContent = oSourceContents.val();
  224. }
  225. else
  226. {
  227. sTextContent = oFormattedContents.contents().find("body").text();
  228. }
  229. if (bMandatory && (sTextContent == ''))
  230. {
  231. bValid = false;
  232. }
  233. else
  234. {
  235. bValid = true;
  236. }
  237. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  238. setTimeout(function(){ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue);}, 500);
  239. }
  240. /*
  241. function UpdateDependentFields(aFieldNames)
  242. {
  243. //console.log('UpdateDependentFields:');
  244. //console.log(aFieldNames);
  245. index = 0;
  246. oWizardHelper.ResetQuery();
  247. oWizardHelper.UpdateWizard();
  248. while(index < aFieldNames.length )
  249. {
  250. sAttCode = aFieldNames[index];
  251. sFieldId = oWizardHelper.GetFieldId(sAttCode);
  252. $('#v_'+sFieldId).html('<img src="../images/indicator.gif" />');
  253. oWizardHelper.RequestAllowedValues(sAttCode);
  254. index++;
  255. }
  256. oWizardHelper.AjaxQueryServer();
  257. }
  258. */
  259. function ResetPwd(id)
  260. {
  261. // Reset the values of the password fields
  262. $('#'+id).val('*****');
  263. $('#'+id+'_confirm').val('*****');
  264. // And reset the flag, to tell it that the password remains unchanged
  265. $('#'+id+'_changed').val(0);
  266. // Visual feedback, None when it's Ok
  267. $('#v_'+id).html('');
  268. }
  269. // Called whenever the content of a one way encrypted password changes
  270. function PasswordFieldChanged(id)
  271. {
  272. // Set the flag, to tell that the password changed
  273. $('#'+id+'_changed').val(1);
  274. }
  275. // Special validation function for one way encrypted password fields
  276. function ValidatePasswordField(id, sFormId)
  277. {
  278. var bChanged = $('#'+id+'_changed').val();
  279. if (bChanged)
  280. {
  281. if ($('#'+id).val() != $('#'+id+'_confirm').val())
  282. {
  283. oFormErrors['err_'+sFormId]++;
  284. if (oFormErrors['input_'+sFormId] == null)
  285. {
  286. // Let's remember the first input with an error, so that we can put back the focus on it later
  287. oFormErrors['input_'+sFormId] = id;
  288. }
  289. // Visual feedback
  290. $('#v_'+id).html('<img src="../images/validation_error.png" style="vertical-align:middle"/>');
  291. return false;
  292. }
  293. }
  294. $('#v_'+id).html(''); //<img src="../images/validation_ok.png" />');
  295. return true;
  296. }
  297. //Special validation function for case log fields, taking into account the history
  298. // to determine if the field is empty or not
  299. function ValidateCaseLogField(sFieldId, bMandatory, sFormId)
  300. {
  301. bValid = true;
  302. if ($('#'+sFieldId).attr('disabled'))
  303. {
  304. bValid = true; // disabled fields are not checked
  305. }
  306. else if (!bMandatory)
  307. {
  308. bValid = true;
  309. }
  310. else
  311. {
  312. if (bMandatory)
  313. {
  314. var count = $('#'+sFieldId+'_count').val();
  315. if ( (count == 0) && ($('#'+sFieldId).val() == '') )
  316. {
  317. // No previous entry and no content typed
  318. bValid = false;
  319. }
  320. }
  321. }
  322. ReportFieldValidationStatus(sFieldId, sFormId, bValid, '');
  323. return bValid;
  324. }
  325. // Validate the inputs depending on the current setting
  326. function ValidateRedundancySettings(sFieldId, sFormId)
  327. {
  328. var bValid = true;
  329. var sExplain = '';
  330. $('#'+sFieldId+' :input[type="radio"]:checked').parent().find(':input[type="string"]').each(function (){
  331. var sValue = $(this).val().trim();
  332. if (sValue == '')
  333. {
  334. bValid = false;
  335. sExplain = Dict.S('UI:ValueMustBeSet');
  336. }
  337. else
  338. {
  339. // There is something... check if it is a number
  340. re = new RegExp('^[0-9]+$');
  341. bValid = re.test(sValue);
  342. if (bValid)
  343. {
  344. var iValue = parseInt(sValue , 10);
  345. if ($(this).hasClass('redundancy-min-up-percent'))
  346. {
  347. // A percentage
  348. if ((iValue < 0) || (iValue > 100))
  349. {
  350. bValid = false;
  351. }
  352. }
  353. else if ($(this).hasClass('redundancy-min-up-count'))
  354. {
  355. // A count
  356. if (iValue < 0)
  357. {
  358. bValid = false;
  359. }
  360. }
  361. }
  362. if (!bValid)
  363. {
  364. sExplain = Dict.S('UI:ValueInvalidFormat');
  365. }
  366. }
  367. });
  368. ReportFieldValidationStatus(sFieldId, sFormId, bValid, sExplain);
  369. return bValid;
  370. }
  371. // Manage a 'duration' field
  372. function UpdateDuration(iId)
  373. {
  374. var iDays = parseInt($('#'+iId+'_d').val(), 10);
  375. var iHours = parseInt($('#'+iId+'_h').val(), 10);
  376. var iMinutes = parseInt($('#'+iId+'_m').val(), 10);
  377. var iSeconds = parseInt($('#'+iId+'_s').val(), 10);
  378. var iDuration = (((iDays*24)+ iHours)*60+ iMinutes)*60 + iSeconds;
  379. $('#'+iId).val(iDuration);
  380. $('#'+iId).trigger('change');
  381. return true;
  382. }
  383. // Called when filling an autocomplete field
  384. function OnAutoComplete(id, event, data, formatted)
  385. {
  386. if (data)
  387. {
  388. // A valid match was found: data[0] => label, data[1] => value
  389. if (data[1] != $('#'+id).val())
  390. {
  391. $('#'+id).val(data[1]);
  392. $('#'+id).trigger('change');
  393. $('#'+id).trigger('extkeychange');
  394. }
  395. }
  396. else
  397. {
  398. if ($('#label_'+id).val() == '')
  399. {
  400. $('#'+id).val(''); // Empty value
  401. }
  402. else
  403. {
  404. $('#'+id).val('$$NULL$$'); // Convention: not a valid value
  405. }
  406. $('#'+id).trigger('change');
  407. }
  408. }