Why isn't this script working to set the multiple ...
# ask-stanley-ai
n
Why isn't this script working to set the multiple select value: /** * @NApiVersion 2.1 * @NScriptType Suitelet */ define(['N/ui/serverWidget', 'N/log', 'N/query'], function(serverWidget, log, query) { function onRequest(context) { if (context.request.method === 'GET') { let requestParams = context.request.parameters; let attendeeQty = parseInt(requestParams.attendeeQty, 10) || 0; let lineIndex = requestParams.lineIndex; let form = serverWidget.createForm({ title: 'Select Employees' }); form.addField({ id: 'custpage_attendee_qty', type: serverWidget.FieldType.INTEGER, label: 'Attendee Quantity' }).updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN }).defaultValue = attendeeQty; form.addField({ id: 'custpage_line_index', type: serverWidget.FieldType.INTEGER, label: 'Line Index' }).updateDisplayType({ displayType: serverWidget.FieldDisplayType.HIDDEN }).defaultValue = lineIndex; let employeeField = form.addField({ id: 'custpage_selected_employees', type: serverWidget.FieldType.MULTISELECT, label: 'Select Employees', source: 'employee' }); form.addSubmitButton({ label: 'Save' }); context.response.writePage(form); } else if (context.request.method === 'POST') { let lineIndex = context.request.parameters.custpage_line_index; let selectedEmployees = context.request.parameters.custpage_selected_employees; log.debug("Raw Selected Employees (Before Processing)", selectedEmployees); // Ensure selectedEmployees is always an array if (!selectedEmployees) { selectedEmployees = []; } else if (typeof selectedEmployees === 'string') { selectedEmployees = selectedEmployees.includes(',') ? selectedEmployees.split(',') : [selectedEmployees]; } // Convert employee IDs to integers let uniqueEmployeeIds = selectedEmployees.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); log.debug("Filtered Unique Employee IDs for Query", uniqueEmployeeIds); let newAttendeeQty = uniqueEmployeeIds.length; log.debug("Final Attendee Quantity", newAttendeeQty); // 🔹 Step 1: Use SuiteQL to Fetch Employee Names (Now Using
runSuiteQLPaged
) let employeeNames = []; if (newAttendeeQty > 0) { let employeeIdsString = uniqueEmployeeIds.map(id =>
'${id}'
).join(", "); // Ensures proper formatting for SuiteQL let sqlQuery = ` SELECT id AS EmployeeID, firstname, lastname FROM employee WHERE id IN (${employeeIdsString}) `; log.debug("Executing SuiteQL Query", sqlQuery); let queryResults = query.runSuiteQLPaged({ query: sqlQuery, pageSize: 1000 }).iterator(); queryResults.each(function(page) { let pageData = page.value.data.asMappedResults(); pageData.forEach(result => { let firstName = result.firstname || ''; let lastName = result.lastname || ''; let fullName = firstName + ' ' + lastName; employeeNames.push(fullName.trim()); log.debug(
Matched Employee - ID: ${result.EmployeeID}
,
Name: ${fullName}
); }); return true; }); } log.debug("Final Selected Employee Names (Matched to IDs)", employeeNames); let responseHtml = ` <script> console.log("Setting values in NetSuite fields..."); window.opener.require(['N/currentRecord'], function(currentRecord) { let rec = currentRecord.get(); rec.selectLine({ sublistId: 'expense', line: ${lineIndex} }); // Log before setting console.log("Attendee Qty: ", ${newAttendeeQty}); console.log("Employee Names: ", "${employeeNames.join(", ")}"); // Update the Attendee Quantity field dynamically rec.setCurrentSublistValue({ sublistId: 'expense', fieldId: 'custcol_attendee_qty', value: ${newAttendeeQty} }); // Update the Selected Employees field with full names rec.setCurrentSublistValue({ sublistId: 'expense', fieldId: 'custcol_attendees_selected", value: "${employeeNames.join(", ")}" }); rec.commitLine({ sublistId: 'expense' }); console.log("Fields updated successfully."); // Reset the suitelet trigger flag window.opener.suiteletTriggered = false; }); window.close(); </script> `; context.response.write(responseHtml); } } return { onRequest: onRequest }; });
c
AI generated answer (using internal Slack threads):
The script is not working to set the multiple select value because the script is trying to set the values of the sublist fields in the 'beforeLoad' event of a User Event script. However, in the 'beforeLoad' event, the record is not yet fully loaded, and the sublist lines are not available to be manipulated. In the 'beforeLoad' event, you can only manipulate the form, not the record's data. This is why the script is not able to set the sublist values. To resolve this issue, you can move the logic to set the sublist values to the 'beforeSubmit' event, where the record is fully loaded and can be manipulated. Alternatively, you can use a client script and set the sublist values in the 'pageInit' or 'fieldChanged' events. Please note that manipulating sublist lines in a User Event script can have performance implications, especially for records with a large number of lines. It's recommended to use a Scheduled Script or Map/Reduce Script for heavy data processing tasks. Also, remember that when working with sublist fields, you need to select the line first using the 'selectLine' method, then set the value using the 'setCurrentSublistValue' method, and finally commit the line using the 'commitLine' method. Here is a sample code snippet for setting sublist values in a 'beforeSubmit' event:
Copy code
javascript
function beforeSubmit(context) {
    var newRecord = context.newRecord;
    var lineCount = newRecord.getLineCount({ sublistId: 'item' });
    for (var i = 0; i < lineCount; i++) {
        newRecord.selectLine({ sublistId: 'item', line: i });
        newRecord.setCurrentSublistValue({ sublistId: 'item', fieldId: 'custcol_myfield', value: 'myvalue' });
        newRecord.commitLine({ sublistId: 'item' });
    }
}
****** Disclaimer: This response was generated by an artificial intelligence assistant based on previous conversations from multiple Slack channels, and may contain inaccuracies or mistakes. ******
Slack thread 1: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.859525263
Slack thread 2: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.857825577
Slack thread 3: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.856692731
Please provide your feedback on this answer.