Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Scripting

ServiceNow Business Rules: Before, After, Async and Display

Learn ServiceNow business rules: before, after, async and display timing, conditions, the current and previous objects, abort actions and common mistakes.

A business rule is server-side logic that runs when a record is displayed, inserted, updated, deleted or queried. It is the classic way to enforce a rule that every path into the data must obey: forms, imports, integrations and scripts all pass through business rules. Flows are often easier, but business rules remain essential, especially for rules that must change a record before it is saved.

Business rules run on a ServiceNow instance. The scripts below are read-only. The stand-ins are JavaScript models for practicing the timing ideas; they are not platform code.

Creating one

Navigate to System Definition > Business Rules and click New. The important fields:

  • Name: describe the effect, such as Set priority from impact and urgency.
  • Table: for example Incident.
  • Active.
  • Advanced: shows the script tab.
  • When to run tab: When, Order, the operation checkboxes (Insert, Update, Delete, Query) and Filter Conditions / Role conditions.
  • Script: the code (with Advanced ticked).

The When field

This is the most important choice.

When Runs Typical use
before After the submit, before the database write Change or validate the current record, abort the save
after Right after the write, in the same transaction Update related records, create child records
async After the write, later, in the background Slow work: calls to other systems, heavy updates
display When the form loads, before it reaches the browser Pass data to client scripts with g_scratchpad

Choose before if you want to modify the record being saved: you set a field on current and the platform saves it, without a second update(). Choose after for side effects on other records. Choose async if a user should not wait.

flowchart LR
    U["User clicks Save"] --> B["Before rules"]
    B --> W["Database write"]
    W --> A["After rules"]
    A --> R["Response to user"]
    W -.-> AS["Async rules run later"]

Before rules can still change the record. After rules cannot change it without another update. Async rules do not delay the user.

current and previous

In a script you get two objects:

  • current: the GlideRecord being saved, with its new values.
  • previous: the same record with the values from before this save (updates only).
JavaScript
(function executeRule(current, previous /*null when async*/) {
  if (current.priority.changesTo(1)) {
    gs.eventQueue('incident.priority.critical', current, current.number, current.assigned_to);
  }
})(current, previous);

Helpful field tests: current.state.changes(), changesTo(value), changesFrom(value), current.isNewRecord(). Never call current.update() in a before rule: it can cause recursion, and the platform saves the record anyway. Calling current.update() in an after rule triggers the rules again, so avoid it too.

Aborting an action

JavaScript
(function executeRule(current, previous) {
  if (current.state == 6 && current.close_notes.nil()) {
    gs.addErrorMessage('Close notes are required before resolving.');
    current.setAbortAction(true);
  }
})(current, previous);

setAbortAction(true) cancels the save in a before rule. nil() tests for an empty value. Where a rule only validates a form, a data policy or UI policy is often a better tool, because they also give immediate feedback (see the forms chapter).

Conditions, order and performance

Use the Filter Conditions field instead of an if at the top of your script when you can. The platform checks the condition first and skips the script entirely when it is false.

Order decides which rule runs first (lower numbers earlier; the default is 100). Two rules touching the same field need distinct orders so the outcome is predictable.

Performance traps:

  1. A rule on Query (a query business rule) runs for every query on that table and adds a filter. It is how row-level restrictions are sometimes built; keep it very small.
  2. Rules that run a GlideRecord query in each execution multiply load. Cache or limit.
  3. Prefer async for work the user does not need immediately.

Debugging

  • Turn on Debug Business Rule (System Diagnostics > Session Debug). A pane at the bottom of the form shows which rules ran, in which order and with which values.
  • Use gs.info() temporarily and remove it afterward.
  • Remember that a rule may not run if another rule aborted, if the filter is false, or if code used setWorkflow(false).

Modeling before and after

The first stand-in shows why a before rule can change the record but an after rule cannot do it for free.

JS Stand-in: before and after rules around a save

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first record has its priority set by the before rule, so the saved row already contains it. The second is stopped before it reaches the database.

The second stand-in models changesTo using the previous values.

JS Stand-in: changesTo with current and previous

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Rules of thumb

  • Use a flow for readable process automation, a business rule for rules every path must obey.
  • Keep each rule small and named by its effect.
  • One responsibility per rule; heavy logic goes to a script include.
  • Never use hard-coded sys_ids; look up by name or use a system property.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which timing lets you set a field on the record being saved without an extra update?

    A before rule runs prior to the write, so changes to current are saved with the record.
  2. 2. What is the display business rule mostly used for?

    Display rules run when a form loads and can store values in g_scratchpad for client scripts.
  3. 3. Which call cancels a save inside a before rule?

    setAbortAction(true) stops the database operation, usually with an error message.
  4. 4. Why avoid current.update() in rules?

    Calling update inside a rule can run the rules again; in a before rule the save already happens anyway.

Summary

  • Business rules run on display, insert, update, delete or query, with timing before, after, async or display.
  • Use before to change the saved record, after for related records, async for slow work.
  • current holds new values and previous the old ones; avoid current.update().
  • Use filter conditions, sensible order and the session debugger.

Next: Client Scripts, UI Scripts and g_form