OBLYTECH Logo
OBLYTECH Logo

ServiceNow Transform Script: onBefore Examples and Variables

A ServiceNow transform script is a script attached to a transform map that runs at a set point in an import. An onBefore script runs at the start of each row, before the source row becomes the target row. Use it to skip rows, block updates, or fill reference fields before the target record is saved.

What a transform script is and where it sits

A transform map moves rows from an import set table into a target table. Field maps handle the simple cases, where one source column feeds one target field. A transform script covers cases a field map cannot express: rejecting a row, stopping an import, looking up a related record, or reacting once the whole load has finished. For the surrounding concepts, see transform maps explained and import sets explained.

Scripts are created from the transform map record. Open the transform map, go to the Transform Scripts related list, and click New. The form has a When field that picks the event the script belongs to. The events are onStart, onBefore, onAfter, onComplete, onForeignInsert, onChoiceCreate and onReject.

When each event runs

The events fall into three groups: those that run once per import, those that run for each row, and those that fire while a related record or a choice value is about to be created during a row.

Event Runs Notes
onStart Once, before any data rows are read Setting ignore or error stops the whole transformation
onBefore At the start of each row, before the source becomes the target Setting ignore skips that row
onAfter At the end of each row, after the source row is saved to the target Reads the saved target
onComplete Once, after all rows are read and transformed Setting error marks the import set as error afterwards
onForeignInsert Before a related, referenced record is created Setting ignore skips creating that record
onChoiceCreate Before a new choice value is created Setting ignore skips creating the choice
onReject When a foreign record or choice creation is rejected The whole row is not saved

The practical consequence is that onBefore is the earliest point where you hold both the incoming row and the target record, so it is the natural place for any decision about whether a row should be processed at all. For the source types that feed an import set, see import set data source types.

Variables available inside an onBefore script

An onBefore script receives these objects.

  • source: the import set row being transformed. Read a value as a property, such as source.u_company.
  • target: the target row being inserted or updated. Set a field by assigning to a property.
  • map: read-only details of the transform map in use, with properties such as name and sys_id.
  • import_set: the import set being transformed.
  • log: writes information about the current import, for example log.info(…). Each log level has its own method.
  • action: the string “insert” or “update”, telling you whether the target row is about to be created or updated.
  • ignore: a Boolean that skips the current row when set to true.
  • error: a Boolean that halts the entire transformation for the import set and reports an error in the Import Set Log.
  • status_message: a custom message returned in the status_message part of the response.
  • error_message: a custom message returned in the error_message part of the response.

ignore versus error in onBefore

These two flags look similar and behave very differently.

Setting ignore to true in onBefore skips the current row. The remaining rows still process. One detail that surprises people is that an onAfter script still runs for the skipped row, so an onAfter script that assumes a saved target needs its own guard.

Setting error to true halts the entire transformation for the import set and reports an error. Use ignore for a bad row and error for a condition that makes the rest of the run pointless.

The same flag changes meaning with the event. In onStart, ignore does not skip a row, because no row has been read yet. It aborts the entire transformation, and setting error there also stops everything.

Example: skip rows with no company name

This onBefore script drops a row when a required value is missing and records why.

var name = source.u_name.toString();

// Make sure a company name has been provided
var company = source.u_company.toString();

if (company.length == 0) {
    ignore = true;
    var info = "No company name, row ignored! " + name;
    log.info(info);
}

The call to toString converts the field object to a string so its length can be tested.

Example: keep the sys_id from the source

When the source system already owns a unique identifier and you want the new target record to carry the same sys_id, set it on insert.

if (action == "insert") {
    target.setNewGuidValue(source.u_sys_id);
}

The check on action limits the script to new records.

To add this as a script, open the table transform map, click New in the Transform Scripts related list, choose onBefore in the When field, enter the script and click Submit.

Example: fill a reference field from a unique value

A source file may hold an email address or user name rather than a sys_id for a related record. An onBefore script can look the record up and write the reference.

var ref = new GlideRecord("sys_user"); // any reference table
ref.addQuery("email", source.email);   // any unique field
ref.query();
if (ref.next()) {
    target.assigned_to = ref.sys_id;   // any reference field on the target
}

This sample assumes the target table has an assigned_to reference field pointing at the User table, and that email identifies a user uniquely. The table, the query field and the reference field can each be swapped for your own. For more on the lookup object used here, see GlideRecord explained. If no user matches, the script leaves assigned_to untouched.

Example: update existing records without inserting new ones

A common request is an import that refreshes records already in the table but must not create new ones. The pattern combines a coalesce field with an onBefore script.

First, mark a field map as Coalesce. The transform then looks for a target record whose value matches the row. A match means an update, and no match means an insert. Then add this onBefore script.

if (action == 'insert')
    ignore = true;

Whenever coalesce finds no match, the action is insert, and the script skips the row. Rows that matched continue as updates.

How coalesce shapes the action your script sees

Coalesce decides whether action arrives as insert or update, so three points matter here.

  • Coalesce only on fields that hold unique values. If several target records match, only the first is updated.
  • With several coalesce fields, the record updates only if all of them match.
  • Matching ignores case by default, and empty values do not match by default. Both can be changed with the Coalesce case sensitive and Coalesce empty fields options. For a fuller treatment of matching, see updating without duplicate records.

When one of several fields should be enough to match, a conditional coalesce script does it. It sits in the Source script of the field map for the sys_id field and returns the sys_id of the target record to update. Typical uses are matching an incident through the caller’s email address by dot-walking, or matching a user on email or user name so that either one can produce a match.

Example: announce a finished import from onComplete

An onComplete script runs once at the end, after all rows are read and transformed. Its source and target variables hold the last row of each table. A script there can create a custom event, which an email notification or a script action then reacts to.

var e = new GlideEvent("myimport_completed", import_set.sys_id, map.sys_id, "");
e.insert();

In onComplete, setting error marks the import set status as error once it completes.

What onAfter, onForeignInsert, onChoiceCreate and onReject add

onBefore decides what happens to a row. The other row-level events handle what surrounds it. For a related kind of server script, see business rules explained.

An onAfter script runs at the end of each row, after the source row is saved to the target. Its action variable reports whether the target was created or updated, and it can set error to halt the transformation. A sample for onAfter places a catalog order when a source flag says the row is new, which shows that follow-up work belongs here rather than in onBefore, where the target has not been saved yet.

onForeignInsert fires before a related, referenced record is created. It receives name, the target field for which the record would be created, and value, the display value from the source. Setting ignore skips creating the related record, while setting error rejects the entire row so nothing is saved for it. onChoiceCreate works the same way for a new choice value. If a foreign record or choice creation is rejected, onReject runs, and the transformation row is not saved.

Frequently asked questions

What does ignore do in an onBefore transform script?

It skips the current row and the import continues with the remaining rows. An onAfter script still runs for the skipped row.

How do I stop an entire import from an onBefore script?

Set error to true. That halts the entire transformation for the import set and reports an error. Setting ignore in an onStart script also stops the whole transformation.

How do I tell inserts from updates in a transform script?

Test the action variable. It holds “insert” when the target row is about to be created and “update” when it is about to be updated.

How do I add an onBefore script to a transform map?

Open the transform map, click New in the Transform Scripts related list, set When to onBefore, enter the script and click Submit.

Can an onBefore script stop new records from being created?

Yes. With a coalesce field set, a script that sets ignore when action equals insert leaves matched rows as updates and skips the rest.