ANS-1845 · SUITESCRIPT DEVELOPMENT

How to Programmatically Add Line Items to NetSuite Records in SuiteScript 1.0

This guide addresses common issues and provides the recommended SuiteScript 1.0 approach for dynamically inserting new line items into sublists on NetSuite records.

Short answer

When adding line items to NetSuite records in SuiteScript 1.0, using nlapiSelectNewLineItem, nlapiSetCurrentLineItemValue, and nlapiCommitLineItem is the preferred method. This approach mimics the UI's "Insert" button, ensuring proper line item creation and avoiding errors associated with direct insertion at specific line numbers.

Scenario

A NetSuite script designed to add line items to a record's sublist, such as an invoice's item sublist, encounters unexpected errors when attempting to use nlapiInsertLineItem during the beforeLoad event. This issue often arises when trying to insert a line at the end of an existing sublist, leading to script failures.

Solution

The nlapiInsertLineItem function, while available in SuiteScript 1.0, can be prone to errors when attempting to insert lines at specific positions, especially at the end of a sublist. A more robust and preferred method in SuiteScript 1.0 for adding new line items is to simulate the user interface's "Insert" button functionality.The problematic approach, which attempts to insert a line at a calculated position (using 1-based indexing typical for SuiteScript 1.0), might look like this:

var lineNumber = nlapiGetLineItemCount('item') + 1;nlapiInsertLineItem('item', lineNumber);nlapiSetLineItemValue('item', 'fieldname', lineNumber, 'value');

The recommended SuiteScript 1.0 approach for adding new line items involves selecting a new line, setting its values, and then committing it. This method ensures the line is properly initialized and added to the sublist.

  1. Select a new line item within the specified sublist.

  2. Set the required field values for the newly selected line.

  3. Commit the new line item to the record.Here is the corrected and preferred SuiteScript 1.0 code snippet:

nlapiSelectNewLineItem('item');nlapiSetCurrentLineItemValue('item', 'fieldname', 'value');nlapiCommitLineItem('item');

This method effectively resolves issues related to inserting line items programmatically.Note on SuiteScript Versions: The functions nlapiInsertLineItem, nlapiSelectNewLineItem, nlapiSetCurrentLineItemValue, and nlapiCommitLineItem are part of SuiteScript 1.

  1. For new development, NetSuite strongly recommends using SuiteScript 2.x, which offers a modular, object-oriented API (e.g., methods from the N/record module) and uses 0-based indexing for sublist lines.

Expert NetSuite Support

Need help with this NetSuite issue?

SuiteScript Development consulting and configuration support

Talk to a consultant