Bite #4: Workflows should never contain current.update()

Can using current.update() within a workflow’s script activity cause harm?

The Scenario

You’re using a script activity in the Change Workflow to look up the value of a particular field on a Change Task that was just closed. You want to update the Change with that same data, and as a result you’re using a code snippet that looks like this:

     var chgTsk = new GlideRecord("change_task");
     chgTsk.addQuery("change_request", current.sys_id);
     chgTsk.addQuery("u_change_task_type", "Implementation");
     chgTsk.query();
     if(chgTsk.next()) {
          current.u_implementation_result = chgTsk.u_result.toString();
          current.update();
     }

The Problem

While this particular code might not cause a problem, using current.update() within a workflow has the potential to cause duplicate updates, or in the worst case scenario: infinite loops.

The Solution

Listen to ServiceNow’s recommendation and never use current.update() inside a business rule. Simply set the value of the field as you normally would, and leave current.update() out of it.
The Workflow Execution engine will update the current record for you.
Example:

     // ... Same code as above ... //
     if(chgTsk.next()) {
          current.u_implementation_result = chgTsk.u_result.toString();
          // I'm intentionally not using any update code here...
          // as the workflow engine will take care of that for me.
     }


Categories: Developers, Scripting Tips

Tags: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: