Application User Interface · Topic 3 of 4

Server Side Scripts

CAD server side scripting: business rule timing, current and previous, GlideRecord queries, script include types, and debugging with the Script Debugger.

  • 5 min
In a nutshell
  • before changes current and can abort; after updates other records; async runs later; display fills g_scratchpad.
  • previous holds the old values and is not available in async rules.
  • Do not call current.update() in a before or after rule on the same record.

What it is

Server side scripts run on the instance, not in the browser. They run whether a record is saved from a form, a list, an import, an API call or another script. That makes them the place for rules that must always hold and for work on other records.

The two main server script types on this exam are business rules, which run when records are read or written, and script includes, reusable code that other scripts call.

Record savedform, list, import, APIBefore business rulechange currentDatabase writeAfter business ruleupdate other records

How it works

Business rule timing

Business rules live in System Definition > Business Rules. Each names a table, the operations (Insert, Update, Delete, Query) and When it runs.

WhenRunsUse it to
beforeBefore the record is writtenChange values on current or abort the save
afterAfter the write, in the same transactionUpdate related records
asyncAfter the write, later, as a scheduled jobSlow work such as integrations, without delaying the user
displayBefore the form is shownFill g_scratchpad for client scripts

The Filter Conditions and Role conditions decide whether the rule runs at all. Ticking Advanced shows the script field.

current and previous

current is the record being processed and previous holds its values before this update. previous is not available in async business rules.

(function executeRule(current, previous /*null when async*/) {
  if (current.getValue('end_date') < current.getValue('start_date')) {
    gs.addErrorMessage('End date must be after start date');
    current.setAbortAction(true);
  }
})(current, previous);

In a before rule you change current directly; the platform saves it. Calling current.update() in a before or after rule on the same record saves it again and can run the rules repeatedly.

GlideRecord

GlideRecord reads and writes table records on the server.

var gr = new GlideRecord('x_acme_loans_request');
gr.addQuery('requested_for', current.requested_for);
gr.addActiveQuery();
gr.query();
while (gr.next()) {
  gs.info('Open loan: ' + gr.getValue('number'));
}

Other common methods are get(sys_id), addEncodedQuery, setLimit, insert, update and deleteRecord. To count or sum many records, GlideAggregate is more efficient than looping.

Script includes

Script includes live in System Definition > Script Includes and run only when called.

KindShapeTypical use
ClasslessOne function named like the script includeA single shared helper
Class basedClass.create() with several methodsA utility library for the app
Client callableExtends AbstractAjaxProcessorAnswers GlideAjax calls from client scripts

The Accessible from setting decides whether only this application scope or all scopes may call it. Inside the scope you call new LoanUtils(); another scope calls new x_acme_loans.LoanUtils().

Choose a business rule when code must run because a record is read or written. Choose a script include when the same logic is needed in several places, such as two business rules and a flow.

Testing and debugging

Set breakpointScript DebuggerTrigger the scriptsave a recordStep throughinspect variablesFix and retest
  • The Script Debugger sets breakpoints and logpoints and steps through server scripts that run in your session, such as business rules on a form save.
  • gs.info, gs.warn, gs.error and gs.debug write to the system log; scoped applications cannot use gs.log.
  • Session Debug options, such as Debug Business Rule, show which rules ran on the current transaction.
  • Scripts - Background lets an administrator run a quick server script in a chosen scope.

How the exam asks about this

  • "Set a field's value automatically whenever a record is saved, from any source." A before business rule that sets the value on current.
  • "Send record data to an external system without making the user wait." An async business rule.
  • "Two business rules and a flow need the same calculation." A script include they all call.

What to remember for the exam

  • before changes current and can abort; after updates other records; async runs later; display fills g_scratchpad.
  • previous holds the old values and is not available in async rules.
  • Do not call current.update() in a before or after rule on the same record.
  • query() then while (next()) is the GlideRecord loop; GlideAggregate counts efficiently.
  • Script includes are classless, class based, or client callable through AbstractAjaxProcessor.
  • The Script Debugger uses breakpoints for scripts running in your session.
Watch out

An async business rule does not run in the user's transaction, so messages it adds never reach the user and it cannot abort the save. Use a before rule for validation.

Common mistakes

Using an after rule to change the same record. The record is already written. Set values in a before rule instead of calling current.update() after the save.

Using a client script for a rule that must always hold. Imports, APIs and server scripts never run client scripts. A business rule on the server applies to every source.

Repeating the same code in several business rules. Put it in a script include and call it, so a fix is made once.

Check yourself

  • Which business rule timing should set a field value on the record being saved?

    A before business rule, which changes current before the record is written so no extra update is needed.

  • Why is previous not useful in an async business rule?

    An async rule runs later as a scheduled job, and previous is not available to it.

  • How does a script in another scope call the script include LoanUtils in the x_acme_loans scope?

    With new x_acme_loans.LoanUtils(), provided the script include is accessible from all application scopes.

Topic 3 of 4 in Application User Interface

Test yourself on Application User Interface

The full ServiceNow CAD question bank has 600 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by ServiceNow. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.