How to Avoid Using a Saved Search on Field Change in a NetSuite Client Script

Using a saved search within the fieldChanged function of a NetSuite client script can lead to performance issues and script delays. Every time a field is modified, the saved search is triggered, which may cause unnecessary load on the system, especially when handling large datasets or frequent field changes.

To improve script efficiency and avoid redundant saved search calls, a better approach is to execute the saved search during the pageInit event and store the results in a global variable. This way, the search results can be referenced directly within the fieldChanged function, eliminating the need to run the search repeatedly.

🚨 Why Avoid Saved Searches in fieldChanged?

  1. Performance Impact: Running a saved search on every field change increases server load and slows down the user interface.
  2. Repeated Queries: Multiple unnecessary calls to the database can lead to governance unit consumption and potential script timeouts.
  3. Redundant Data Retrieval: If the search results remain static during the session, executing it multiple times is inefficient.

✅ Optimal Approach: Using Saved Search in pageInit

Step 1: Run Saved Search in pageInit and Store in Global Variable

Use the pageInit function to execute the saved search and store the results in a global variable. This ensures that the search is executed only once when the record is loaded.

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 */
define(['N/search'], function(search) {
    var searchResults = {}; // Global variable to store search results

    function pageInit(context) {
        try {
            // Run the saved search once and store results
            var mySearch = search.load({ id: 'customsearch_my_saved_search' });
            var searchResultSet = mySearch.run();
            searchResults = getSearchData(searchResultSet);
        } catch (e) {
            console.log('Error loading search: ' + e.message);
        }
    }

    function getSearchData(resultSet) {
        var resultObj = {};
        resultSet.each(function(result) {
            var key = result.getValue({ name: 'internalid' });
            var value = result.getValue({ name: 'custitem_my_custom_field' });
            resultObj[key] = value;
            return true;
        });
        return resultObj;
    }

Step 2: Use Stored Data in fieldChanged

When a field changes, instead of calling the saved search, refer to the global variable for required values.

    function fieldChanged(context) {
        var fieldId = context.fieldId;

        // Check if the relevant field has been changed
        if (fieldId === 'item') {
            var itemId = context.currentRecord.getValue({ fieldId: 'item' });

            // Use the stored search results
            if (searchResults[itemId]) {
                console.log('Item Found: ' + searchResults[itemId]);
            } else {
                console.log('Item not found in search results');
            }
        }
    }

    return {
        pageInit: pageInit,
        fieldChanged: fieldChanged
    };
});

📈 Benefits of This Approach

  1. Improved Performance: Running the search only once prevents repeated hits to the server, resulting in a smoother UI experience.
  2. Reduced Governance Consumption: Minimizes the usage of governance units by eliminating redundant search executions.
  3. Consistent Data Usage: Using a preloaded dataset ensures that the data remains consistent throughout the session.

âš¡ Additional Tips

  • Ensure that the search used in pageInit is optimized and returns only the necessary data.
  • Validate the global variable in fieldChanged to handle edge cases where the search may return no results.
  • If search results need to be refreshed dynamically, consider using setTimeout or other strategies to periodically reload the search results.

By adopting this approach, you can enhance script performance, reduce governance consumption, and streamline the user experience in NetSuite.

Leave a comment

Your email address will not be published. Required fields are marked *