To add fields to a form in a Suitelet using a configuration array, you can use a similar approach as you’ve outlined. Here’s a complete example of a Suitelet that dynamically adds fields to a form based on the provided field configurations:
/**
* @NApiVersion 2.x
* @NScriptType Suitelet
*/
define([‘N/ui/serverWidget’], function(serverWidget) {
function onRequest(context) {
if (context.request.method === ‘GET’) {
var form = serverWidget.createForm({
title: ‘Dynamic Fields Form’
});
// Field configuration array
var fieldConfigs = [
{ id: ‘custpage_jj_customer’, type: serverWidget.FieldType.SELECT, label: ‘Customer’, source: ‘customer’ },
{ id: ‘custpage_jj_location’, type: serverWidget.FieldType.SELECT, label: ‘Location’, source: ‘location’ },
{ id: ‘custpage_jj_projectcode’, type: serverWidget.FieldType.SELECT, label: ‘Project Id’, source: ‘project’ }
];
// Function to add fields based on the configuration array
function addFields(formObj, fieldConfigs) {
fieldConfigs.forEach(function(config) {
var field = formObj.addField({
id: config.id,
type: config.type,
label: config.label,
source: config.source || null
});
});
}
// Add fields to the form
addFields(form, fieldConfigs);
// Write the form to the response
context.response.writePage(form);
}
}
return {
onRequest: onRequest
};
});