forms-json-utils.js 12 KB

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