Learn how to create a map/reduce script to load and save records

Introduction

User event scripts are commonly created to update data on a record before it is saved. This is referred to as “Before Submit”. But what if we want to have this logic happen on records which already exist?  There are several approaches here.  One is to create a CSV import of the records and update a field that is inconsequential to trigger the user event script.  This may be okay, but you then have strange data on your records.  Another approach is to do a mass update of the records and not update any fields.  This will work but it will only trigger the user event script in the “XEDIT” context.  In the “XEDIT” context, only the fields which are being updated are available unless you load the record.  A third approach is to create a map/reduce script to load and save records based on a saved search.  The loading and saving of the record will trigger user event scripts which execute using the “EDIT” context.  I will detail this last approach.

Step 1: Define a saved search for the records which need to be loaded and saved

As an example, I created a saved search of sales orders.  Make sure the “Public” checkbox is checked.  See below:

 

 

Step 2: Upload the Script to SuiteScripts folder

  1. Create a file with the code snippet below.
  2. Go to Documents->Files->SuiteScripts.
  3. Add the file here.

Notice this code assumes you are working with some type of transaction.  This can easily be changed for other record types (Entity, Activity, etc.).

 

/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 * @NModuleScope SameAccount
 *
 */

define([ 'N/runtime', 'N/record', 'N/search'],
(runtime, record, search) => {

   getInputData = () => {
        log.debug('===START===');
        const scriptObj = runtime.getCurrentScript();
        const savedSearch = scriptObj.getParameter({name: 'custscript_saved_search'});
        const searchObj = search.load({
            id: savedSearch
        });
        return searchObj;
    }

    map = (context) => {
        try {
            const fieldLookUp = search.lookupFields({
                type: 'transaction',
                id: context.key,
                columns: ['recordtype']
            });

            const transRecord = record.load({
                type: fieldLookUp.recordtype,
                id: context.key
            });

            transRecord.save({
                enableSourcing : true,
                ignoreMandatoryFields : true
            });
        }
        catch(e) {
            log.error('Error loading and saving', JSON.stringify(e));
        }
    }

    summarize = (summary) => {
        log.debug('===END===');
    }

    return {
        getInputData: getInputData,
        map: map,
        summarize: summarize
    };

});

Step 3: Create Map/Reduce Script

  1. Go to Customization->Scripting->Scripts->New.
  2. Type the name of your script and click “Create Script Record”.
  3. Give the record a name and optionally an ID.
  4. Save.
  5. Go to the “Parameters” tab and add a parameter.
  6. Name of parameter will be “Saved Search”.  Type is List/Record.  List/Record is “Saved Search”.  For the “ID” put “_saved_search”.
  7. Save.  The parameter should look like this:

 

 

  1. Now deploy the script by doing “Save and Deploy”.
  2. On the parameters tab, select your saved search by typing in the name.
  3. Save.

 

Step 4: Run the Map/Reduce Script

  1. On the script deployment, select “Save and Execute”.

Once the script has finished processing, you will see that your user event script was triggered on each record.

Conclusion

Needing to trigger user event scripts on old records is a common request I run into.  I hope you enjoyed reading about this solution.  If you need help scripting or customizing NetSuite please contact Suite Tooth consulting here to set up a free consultation.

If you liked this article, please sign up for my newsletter to get these delivered to your inbox here.

Follow on
Jaime Requena Chief Executive Officer

Jaime Requena is a seasoned NetSuite Consultant and Solutions Architect, known for delivering WHITE GLOVE service to businesses. With 15+ years of experience and 3x certifications in ERP, Developer, and Admin, Jaime specializes in highly customized NetSuite accounts, transforming operations for 200+ satisfied customers all across the globe.

Get Connected

How can we help?


    Stay in the loop with Suite Tooth Consulting!

    We aim to bring unmatched expertise and professionalism to your NetSuite initiatives. Let’s talk about how our NetSuite consultancy can make a difference!

    Global Client Satisfaction

    Client Testimonials

    It’s Been 4+ Years Now And We Have Worked With Hundreds Of Clients, Building Our Way To The Top, One Happy Client After Another! Their Voices Of Satisfaction Serve As A Testament To Our Success –