1. /**
  2. * Reads web form configuration and applies default values for sandbox usage.
  3. * @param {object} formConfigs - An object containing form configurations.
  4. * Each key is a form ID, and the value is an object
  5. * with 'fields' (array of field configurations) and 'defaults' (object of default values).
  6. * @returns {object} - An object containing the populated form data. Returns null if formConfigs is invalid.
  7. */
  8. function populateForms(formConfigs) {
  9. if (!formConfigs || typeof formConfigs !== 'object') {
  10. console.error("Invalid formConfigs provided.");
  11. return null;
  12. }
  13. const formData = {};
  14. for (const formId in formConfigs) {
  15. if (formConfigs.hasOwnProperty(formId)) {
  16. const formConfig = formConfigs[formId];
  17. const fields = formConfig.fields || [];
  18. const defaults = formConfig.defaults || {};
  19. const formDataForForm = {};
  20. for (const fieldConfig of fields) {
  21. const fieldId = fieldConfig.id;
  22. const fieldType = fieldConfig.type; // e.g., 'text', 'select', 'date'
  23. const label = fieldConfig.label;
  24. const required = fieldConfig.required || false;
  25. const defaultValue = defaults[fieldId] || null; // Use default if available
  26. // Apply default value based on field type
  27. let value = defaultValue;
  28. if (value === undefined) {
  29. value = ''; // Default to empty string if no default
  30. }
  31. if (fieldType === 'select') {
  32. if (defaultValue !== undefined) {
  33. value = defaultValue;
  34. } else {
  35. value = '';
  36. }
  37. }
  38. else if (fieldType === 'date') {
  39. if (defaultValue !== undefined) {
  40. value = new Date(defaultValue); //Ensure date object
  41. } else {
  42. value = '';
  43. }
  44. }
  45. formDataForForm[fieldId] = value;
  46. }
  47. formId = formId; //ensure formId is valid for assignment
  48. formData[formId] = formDataForForm;
  49. }
  50. }
  51. return formData;
  52. }

Add your comment