/**
* Reads web form configuration and applies default values for sandbox usage.
* @param {object} formConfigs - An object containing form configurations.
* Each key is a form ID, and the value is an object
* with 'fields' (array of field configurations) and 'defaults' (object of default values).
* @returns {object} - An object containing the populated form data. Returns null if formConfigs is invalid.
*/
function populateForms(formConfigs) {
if (!formConfigs || typeof formConfigs !== 'object') {
console.error("Invalid formConfigs provided.");
return null;
}
const formData = {};
for (const formId in formConfigs) {
if (formConfigs.hasOwnProperty(formId)) {
const formConfig = formConfigs[formId];
const fields = formConfig.fields || [];
const defaults = formConfig.defaults || {};
const formDataForForm = {};
for (const fieldConfig of fields) {
const fieldId = fieldConfig.id;
const fieldType = fieldConfig.type; // e.g., 'text', 'select', 'date'
const label = fieldConfig.label;
const required = fieldConfig.required || false;
const defaultValue = defaults[fieldId] || null; // Use default if available
// Apply default value based on field type
let value = defaultValue;
if (value === undefined) {
value = ''; // Default to empty string if no default
}
if (fieldType === 'select') {
if (defaultValue !== undefined) {
value = defaultValue;
} else {
value = '';
}
}
else if (fieldType === 'date') {
if (defaultValue !== undefined) {
value = new Date(defaultValue); //Ensure date object
} else {
value = '';
}
}
formDataForForm[fieldId] = value;
}
formId = formId; //ensure formId is valid for assignment
formData[formId] = formDataForForm;
}
}
return formData;
}
Add your comment