forms-json-utils.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 AjaxGetValuesDef(oObj, sClass, sAttCode, iFieldId)
  85. //{
  86. // var oJSON = document.getElementById(sJsonFieldId);
  87. // $.get('ajax.render.php?class=' + sClass + '&json_obj=' + oJSON.value + '&att_code=' + sAttCode,
  88. // { operation: "allowed_values" },
  89. // function(data){
  90. // //$('#field_'+iFieldId).html(data);
  91. // }
  92. // );
  93. //}
  94. //
  95. //function AjaxGetDefaultValue(oObj, sClass, sAttCode, iFieldId)
  96. //{
  97. // // Asynchronously call the server to provide a default value if the field is
  98. // // empty
  99. // if (oObj['m_aCurrValues'][sAttCode] == '')
  100. // {
  101. // var oJSON = document.getElementById(sJsonFieldId);
  102. // $.get('../pages/ajax.render.php?class=' + sClass + '&json_obj=' + oJSON.value + '&att_code=' + sAttCode,
  103. // { operation: "default_value" },
  104. // function(json_data){
  105. // var oObj = ReloadObjectFromServer(json_data);
  106. // UpdateFieldFromObject(iFieldId, aFieldsMap, oObj)
  107. // }
  108. // );
  109. // }
  110. //}
  111. function OnUnload(sTransactionId)
  112. {
  113. if (!window.bInSubmit)
  114. {
  115. // If it's not a submit, then it's a "cancel" (Pressing the Cancel button, closing the window, using the back button...)
  116. $.post('../pages/ajax.render.php', {operation: 'on_form_cancel', transaction_id: sTransactionId }, function()
  117. {
  118. // Do nothing for now...
  119. });
  120. }
  121. }
  122. function OnSubmit(sFormId)
  123. {
  124. window.bInSubmit=true; // This is a submit, make sure that when the page gets unloaded we don't cancel the action
  125. var bResult = CheckFields(sFormId, true);
  126. if (!bResult)
  127. {
  128. window.bInSubmit = false; // Submit is/will be canceled
  129. }
  130. return bResult;
  131. }
  132. // Store the result of the form validation... there may be several forms per page, beware
  133. var oFormErrors = { err_form0: 0 };
  134. function CheckFields(sFormId, bDisplayAlert)
  135. {
  136. $('#'+sFormId+' :submit').attr('disable', 'disabled');
  137. $('#'+sFormId+' :button[type=submit]').attr('disable', 'disabled');
  138. firstErrorId = '';
  139. // The two 'fields' below will be updated when the 'validate' event is processed
  140. oFormErrors['err_'+sFormId] = 0; // Number of errors encountered when validating the form
  141. oFormErrors['input_'+sFormId] = null; // First 'input' with an error, to set the focus to it
  142. $('#'+sFormId+' :input').each( function()
  143. {
  144. validateEventResult = $(this).trigger('validate', sFormId);
  145. }
  146. );
  147. if(oFormErrors['err_'+sFormId] > 0)
  148. {
  149. if (bDisplayAlert)
  150. {
  151. alert('Please fill-in all mandatory fields before continuing.');
  152. }
  153. $('#'+sFormId+' :submit').attr('disable', '');
  154. $('#'+sFormId+' :button[type=submit]').attr('disable', '');
  155. if (oFormErrors['input_'+sFormId] != null)
  156. {
  157. $('#'+oFormErrors['input_'+sFormId]).focus();
  158. }
  159. }
  160. return (oFormErrors['err_'+sFormId] == 0); // If no error, submit the form
  161. }
  162. function ReportFieldValidationStatus(sFieldId, sFormId, bValid)
  163. {
  164. if (bValid)
  165. {
  166. // Visual feedback - none when it's Ok
  167. $('#v_'+sFieldId).html(''); //<img src="../images/validation_ok.png" />');
  168. }
  169. else
  170. {
  171. // Report the error...
  172. oFormErrors['err_'+sFormId]++;
  173. if (oFormErrors['input_'+sFormId] == null)
  174. {
  175. // Let's remember the first input with an error, so that we can put back the focus on it later
  176. oFormErrors['input_'+sFormId] = sFieldId;
  177. }
  178. // Visual feedback
  179. $('#v_'+sFieldId).html('<img src="../images/validation_error.png" style="vertical-align:middle"/>');
  180. }
  181. }
  182. function ValidateField(sFieldId, sPattern, bMandatory, sFormId, nullValue)
  183. {
  184. var bValid = true;
  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. }
  200. else if (currentVal == nullValue)
  201. {
  202. // An empty field is Ok...
  203. bValid = true;
  204. }
  205. else if (sPattern != '')
  206. {
  207. re = new RegExp(sPattern);
  208. //console.log('Validating field: '+sFieldId + ' current value: '+currentVal + ' pattern: '+sPattern );
  209. bValid = re.test(currentVal);
  210. }
  211. }
  212. ReportFieldValidationStatus(sFieldId, sFormId, bValid);
  213. //console.log('Form: '+sFormId+' Validating field: '+sFieldId + ' current value: '+currentVal+' pattern: '+sPattern+' result: '+bValid );
  214. return true; // Do not stop propagation ??
  215. }
  216. function ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue)
  217. {
  218. var bValid;
  219. var sTextContent;
  220. // Get the contents without the tags
  221. var oFormattedContents = $("#cke_"+sFieldId+" iframe");
  222. if (oFormattedContents.length == 0)
  223. {
  224. var oSourceContents = $("#cke_"+sFieldId+" textarea.cke_source");
  225. sTextContent = oSourceContents.val();
  226. }
  227. else
  228. {
  229. sTextContent = oFormattedContents.contents().find("body").text();
  230. }
  231. if (bMandatory && (sTextContent == ''))
  232. {
  233. bValid = false;
  234. }
  235. else
  236. {
  237. bValid = true;
  238. }
  239. ReportFieldValidationStatus(sFieldId, sFormId, bValid);
  240. setTimeout(function(){ValidateCKEditField(sFieldId, sPattern, bMandatory, sFormId, nullValue);}, 500);
  241. }
  242. /*
  243. function UpdateDependentFields(aFieldNames)
  244. {
  245. //console.log('UpdateDependentFields:');
  246. //console.log(aFieldNames);
  247. index = 0;
  248. oWizardHelper.ResetQuery();
  249. oWizardHelper.UpdateWizard();
  250. while(index < aFieldNames.length )
  251. {
  252. sAttCode = aFieldNames[index];
  253. sFieldId = oWizardHelper.GetFieldId(sAttCode);
  254. $('#v_'+sFieldId).html('<img src="../images/indicator.gif" />');
  255. oWizardHelper.RequestAllowedValues(sAttCode);
  256. index++;
  257. }
  258. oWizardHelper.AjaxQueryServer();
  259. }
  260. */
  261. function ResetPwd(id)
  262. {
  263. // Reset the values of the password fields
  264. $('#'+id).val('*****');
  265. $('#'+id+'_confirm').val('*****');
  266. // And reset the flag, to tell it that the password remains unchanged
  267. $('#'+id+'_changed').val(0);
  268. // Visual feedback, None when it's Ok
  269. $('#v_'+id).html('');
  270. }
  271. // Called whenever the content of a one way encrypted password changes
  272. function PasswordFieldChanged(id)
  273. {
  274. // Set the flag, to tell that the password changed
  275. $('#'+id+'_changed').val(1);
  276. }
  277. // Special validation function for one way encrypted password fields
  278. function ValidatePasswordField(id, sFormId)
  279. {
  280. var bChanged = $('#'+id+'_changed').val();
  281. if (bChanged)
  282. {
  283. if ($('#'+id).val() != $('#'+id+'_confirm').val())
  284. {
  285. oFormErrors['err_'+sFormId]++;
  286. if (oFormErrors['input_'+sFormId] == null)
  287. {
  288. // Let's remember the first input with an error, so that we can put back the focus on it later
  289. oFormErrors['input_'+sFormId] = id;
  290. }
  291. // Visual feedback
  292. $('#v_'+id).html('<img src="../images/validation_error.png" style="vertical-align:middle"/>');
  293. return false;
  294. }
  295. }
  296. $('#v_'+id).html(''); //<img src="../images/validation_ok.png" />');
  297. return true;
  298. }
  299. // Manage a 'duration' field
  300. function UpdateDuration(iId)
  301. {
  302. var iDays = parseInt($('#'+iId+'_d').val(), 10);
  303. var iHours = parseInt($('#'+iId+'_h').val(), 10);
  304. var iMinutes = parseInt($('#'+iId+'_m').val(), 10);
  305. var iSeconds = parseInt($('#'+iId+'_s').val(), 10);
  306. var iDuration = (((iDays*24)+ iHours)*60+ iMinutes)*60 + iSeconds;
  307. $('#'+iId).val(iDuration);
  308. $('#'+iId).trigger('change');
  309. return true;
  310. }
  311. // Called when filling an autocomplete field
  312. function OnAutoComplete(id, event, data, formatted)
  313. {
  314. if (data)
  315. {
  316. // A valid match was found: data[0] => label, data[1] => value
  317. if (data[1] != $('#'+id).val())
  318. {
  319. $('#'+id).val(data[1]);
  320. $('#'+id).trigger('change');
  321. $('#'+id).trigger('extkeychange');
  322. }
  323. }
  324. else
  325. {
  326. if ($('#label_'+id).val() == '')
  327. {
  328. $('#'+id).val(''); // Empty value
  329. }
  330. else
  331. {
  332. $('#'+id).val('$$NULL$$'); // Convention: not a valid value
  333. }
  334. $('#'+id).trigger('change');
  335. }
  336. }