Casebook01 · SuiteScript
The script that saves the record twice
An afterSubmit script loads the record it just saved, changes one field and saves it again. Every save now costs two, and every other script runs twice.
- Casebook 01
- SuiteScript
What you notice
Saving a sales order or invoice takes several seconds longer than it should. Sometimes a workflow email goes out twice, or a field set by one script is overwritten by another.
Why it happens
In SuiteScript 1.0 it was common to write an afterSubmit script like this: load the record that was just saved, set one field, submit it again. The second submit is a full save. It re-runs every user event script and workflow on the record, so the work of one save happens twice, and some of it can loop.
The fix in 2.1
If the value can be known before the save, set it in beforeSubmit while the record is still in memory. No second save happens.
const beforeSubmit = (context) => {
const rec = context.newRecord;
const sourceId = rec.getValue({ fieldId: 'createdfrom' });
if (sourceId) rec.setValue({ fieldId: 'custbody_source_checked', value: true });
};
If it really has to happen after the save (for example, it needs the new record’s ID), update only that field with record.submitFields. It is far cheaper than a load and save, and you can switch off sourcing.
What to check in your account
Search your scripts for afterSubmit functions that call nlapiLoadRecord or record.load on the same record type and ID, followed by a submit. Each one is a candidate.