Skip to content
All quick references

ServiceNow Scripting

33 snippets · 11 sections

Server-side and client-side scripting patterns for the Now Platform: GlideRecord, GlideAggregate, g_form, REST, and the encoded query syntax..

01

GlideRecord Basics

What is a GlideRecord?

  • Used for database operations instead of writing SQL queries
  • An object containing zero or more records from the same table (ordered list)
  • Contains records (rows) and fields (columns)
  • Executes server-side

Strategy for building a query

  • 1. Create a GlideRecord object for the table of interest
  • 2. Build the query condition(s) - addQuery()
  • 3. Execute the query - query()
  • 4. Process returned records with script logic

Query builder methods

MethodPurpose
addQuery(f, v)AND condition, defaults to =
addQuery(f, op, v)Explicit operator: >, <=, IN, LIKE
addOrCondition(f, v)OR - called on the returned QueryCondition
addEncodedQuery(q)Paste a query string from the list filter
addNullQuery(f)Field is empty
addNotNullQuery(f)Field is not empty
addActiveQuery()Shorthand for active=true
orderBy(f) / orderByDesc(f)Sort ascending / descending
setLimit(n)Cap rows returned
chooseWindow(a, b)Row-range window (pagination)

Basic query example

var myObj = new GlideRecord('change_request');
myObj.addQuery('category', '=', 'Hardware');
myObj.addQuery('priority', '!=', 1);
myObj.query();

addOrCondition() - OR logic

var myObj = new GlideRecord('change_request');
var q1 = myObj.addQuery('category', '=', 'Hardware');
q1.addOrCondition('priority', '!=', 1);
myObj.query();

// Equivalent, chained in one line
myObj.addQuery('category', '=', 'Hardware').addOrCondition('priority', '!=', 1);
02

Encoded Queries

Operators

TokenMeaning
=Equals
!=Not equals
> < >= <=Greater / less than
LIKEContains
NOTLIKEDoes not contain
STARTSWITHStarts with
ENDSWITHEnds with
INValue in comma list
NOT INValue not in comma list
ISEMPTYField is empty
ISNOTEMPTYField is populated
ANYTHINGMatches all (useful placeholder)
BETWEENpriorityBETWEEN1@3

Joining conditions

TokenMeaning
^AND
^OROR
^NQNew query (separate OR group)
^ORDERBYSort ascending
^ORDERBYDESCSort descending
^EQTerminates the query string

Real examples

active=true^priority<=2^assignment_groupISNOTEMPTY

stateIN1,2,3^ORDERBYDESCsys_created_on

short_descriptionLIKEpassword^ORdescriptionLIKEpassword

sys_created_on>javascript:gs.beginningOfLastMonth()

assigned_to=javascript:gs.getUserID()

addEncodedQuery() usage

glideRecordObject.addEncodedQuery('where clauses');

myObj.addEncodedQuery('approval=approved^assigned_to=681b365ec0a80164000fb0b05854a0cd^ORassigned_to=sockmonkeysrule86753O9106c6be7f1^end_dateONThisyear@javascript:gs.beginningOfThisYear()@javascript:gs.endOfThisYear()');
03

Insert, Update, Delete

Update

var incGR = new GlideRecord('incident');
incGR.addQuery('problem_id', '=', current.sys_id);
incGR.query();

while (incGR.next()) {
  incGR.work_notes = "Related Problem " + current.number + " closed with the following Close Notes:\n\n" + current.close_notes;
  incGR.update();
}
04

GlideAggregate

Confirm records returned

var myObj = new GlideRecord('incident');
myObj.addQuery('caller_id', current.caller_id);
myObj.query();
var retRows = myObj.getRowCount();
gs.info("Returned number of rows = " + retRows);

var count = new GlideAggregate('incident');
count.addQuery('caller_id', current.caller_id);
count.addAggregate('COUNT');
count.query();
var incidents = 0;
if (count.next()) {
  incidents = count.getAggregate('COUNT');
}
gs.info("Returned number of rows = " + incidents);
05

GlideQuery

An alternative to GlideRecord

  • Server-side API for querying data
  • Written in 100% JavaScript (global Script Include)
  • Uses GlideRecord behind the scenes
Guided by three principles: Fail Fast -improve the feedback loop, surface errors as soon as possible. Be JavaScript -behaves like normal JavaScript, unlike GlideRecord's mix of Java and JavaScript elements. Be Expressive -do more with less code; fluent, chainable style.

Create, Retrieve, Update, Delete (CRUD)

// Create
new GlideQuery('sys_user')
  .insert({
    user_name: 'sock.monkey',
    first_name: 'Sock',
    last_name: 'Monkey',
    roles: 'admin'
  })
  .get();

// Retrieve
new GlideQuery('sys_user')
  .where('user_name', 'sock.monkey')
  .select('sys_id', 'roles')
  .forEach(function(u) {
    gs.info('sys_id = ' + u.sys_id + '\n' + 'roles = ' + u.roles);
  });

// Update
new GlideQuery('sys_user')
  .where('sys_id', '08a205f48749fd1024d4a71d0ebb35db')
  .update({
    roles: 'itil'
  });

// Delete
new GlideQuery('sys_user')
  .where('active', true)
  .where('user_name', 'sock.monkey')
  .deleteMultiple();
06

GlideSystem (gs)

What is gs?

  • Server-side utility API - available almost everywhere server scripts run (Business Rules, Script Includes, Scheduled Jobs)
  • Provides helpful utilities: logging, current-user info, system properties, date/time, events
  • Not available client-side

Common methods

MethodPurpose
gs.info/warn/error(msg)Write to the system log at that level
gs.getUserID()sys_id of the currently logged-in user
gs.getUserName()user_name of the currently logged-in user
gs.getUser().getDisplayName()Full display name of the current user
gs.hasRole(role)Check if the current user has a role
gs.getProperty(name, default)Read a system property
gs.nowDateTime()Current date/time as a UTC string
gs.addInfoMessage(msg) / addErrorMessage(msg)Queue a message shown on the user's next page load
gs.eventQueue(name, current, p1, p2)Fire an event for an Event Rule/Script Action to catch

Logging pattern

gs.info("[MyScriptInclude] Processing record: " + current.number);

try {
  // risky work
} catch (e) {
  gs.error("[MyScriptInclude] Failed for " + current.sys_id + ": " + e.message);
}
07

GlideDateTime

What is GlideDateTime?

  • Represents a date/time value, stored and compared internally in UTC
  • Converts to/from the current user's timezone for display
  • Use it instead of the JavaScript Date object for anything saved to a date/time field

Common methods

MethodPurpose
new GlideDateTime()Current date/time
new GlideDateTime('2024-01-01 08:00:00')Parse a UTC-formatted string
addDays(n) / addSeconds(n)Date math - also addWeeks(), addMonths()
getDisplayValue()Value formatted in the user's timezone
getValue()Raw UTC string, yyyy-MM-dd HH:mm:ss
before(gdt) / after(gdt)Compare against another GlideDateTime
compareTo(gdt)-1 / 0 / 1, like Java's compareTo

Duration between two dates

var start = new GlideDateTime(current.opened_at);
var end = new GlideDateTime(current.closed_at);

var duration = GlideDateTime.subtract(start, end);
gs.info("Duration: " + duration.getDisplayValue());

Check current time against a schedule

var schedule = new GlideSchedule("090eecae0a0a0b260077e1dfa71da828");
var currentDateTime = new GlideDateTime();
if (schedule.isInSchedule(currentDateTime)) {
    gs.print("The schedule is active.");
} else {
    gs.print("The schedule is not active.");
}
08

Client Scripts - g_form

The three script types

TypeRuns when
onLoadThe form finishes loading - good for setting initial field state
onChangeA specific field's value changes - receives oldValue/newValue
onSubmitThe form is submitted, before save - return false to stop the submit
A fourth type, onCellEdit, fires on inline list edits instead of a form.

Common g_form methods

MethodPurpose
g_form.getValue(field)Read a field's value
g_form.setValue(field, value)Set a field's value
g_form.getDisplayValue(field)Read a reference field's display value
g_form.setMandatory(field, bool)Toggle mandatory
g_form.setReadOnly(field, bool)Toggle read-only
g_form.setVisible(field, bool)Show/hide a field
g_form.addInfoMessage(msg) / addErrorMessage(msg)Show a message on the form immediately
g_form.getReference(field, callback)Async-fetch the full record behind a reference field

onChange skeleton

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue === '') {
    return;
  }

  if (newValue === 'critical') {
    g_form.setMandatory('assignment_group', true);
    g_form.addInfoMessage('Critical priority requires an assignment group.');
  }
}
09

Business Rules

When to run

TimingRunsUse for
before queryBefore the DB query executes (sync)Restrict/filter what records come back - no ACL-style "rows removed" message
displayAfter the query, before the form rendersPopulate g_scratchpad so client scripts can read values with no server round-trip
beforeAfter submit, before the write (sync)Modifying current before it is written - no update() needed
afterAfter submit *and* after the write (sync)Cascading changes to *other* records once this one is saved
asyncIn the background as a scheduled jobSlow work (notifications, SLA calcs), no previous - prefer over after when possible; order multiple with priority
Order of execution: before query → display → before → after → async. Before/after/query rules run synchronously - each must finish before the next starts - while async runs independently so the user's transaction isn't held up.
10

Script Includes

Three types of Script Includes

TypeBehavior
Store one classless functionOne re-usable function; server-side only; a.k.a. "on demand"
Define a new classCollection of functions; callable from client-side scripts; convention is to suffix the name with Utils (e.g. TravelRequestUtils)
Extend an existing classAdds functionality to an existing class (typically AbstractAjaxProcessor); callable from client-side scripts

Classless / on-demand Script Include

function hasRoleExactly(userSysID, roleString) {
  try {
    var roleGr = new GlideRecord("sys_user_role");
    if (roleGr.get('name', roleString)) {

      var role = roleGr.getValue('sys_id');
      var gr = new GlideRecord("sys_user_has_role");
      gr.addQuery("user", userSysID);
      gr.addQuery("role", role);
      gr.query();
      if (gr.next()) {
        return true;
      } else {
        return false;
      }
    }
  } catch (error) {
    gs.error("Error in Script Include hasRoleExactly: " + error);
  }
}

Define a new class - global properties

var UserProfileUtils = Class.create();
UserProfileUtils.prototype = {
  initialize: function() {
    this.userRecord = new GlideRecord('sys_user');
    this.userRecord.get(gs.getUserId());
  },

  getFullUserName: function() {
    return this.userRecord.getDisplayValue('name');
  },

  getUserDept: function() {
    return this.userRecord.getDisplayValue('department');
  },

  type: 'UserProfileUtils'
};

Extend AbstractAjaxProcessor

var HelloWorld = Class.create();
HelloWorld.prototype = Object.extendsObject(AbstractAjaxProcessor, {
  alertGreeting: function() {
    return "Hello " + this.getParameter('sysparm_user_name') + "!";
  }
});

Calling a Script Include client-side - GlideAjax

var greeting = new GlideAjax('HelloWorld');
greeting.addParam('sysparm_name', 'alertGreeting');
greeting.addParam('sysparm_user_name', 'Ruth');
greeting.getXML(HelloWorldParse);

function HelloWorldParse(response) {
  var answerFromXML = response.responseXML
    .documentElement.getAttribute("answer");
  alert(answerFromXML);
}

Returning JSON from a Script Include

var CallerIncidents = Class.create();
CallerIncidents.prototype = Object.extendsObject(AbstractAjaxProcessor, {

  getCallersIncs: function() {
    var incArray = []; //Create an empty array

    var callersRecords = new GlideRecord('incident');
    callersRecords.addQuery('caller_id', this.getParameter('sysparm_callerID'));
    callersRecords.query();

    while (callersRecords.next()) {
      //Build the array of objects
      var incDetails = {};
      incDetails.number = callersRecords.number.toString();
      incDetails.priority = callersRecords.priority.getDisplayValue();
      incDetails.shortDesc = callersRecords.short_description.toString();
      incArray.push(incDetails);
    }

    //Create a string from a JSON object and pass it back to the calling script
    return JSON.stringify(incArray);
  },

  type: 'CallerIncidents'
});

Parsing a JSON response client-side

//Create a GlideAjax object and call the Script Include
var incGA = new GlideAjax('CallerIncidents');
incGA.addParam('sysparm_name', 'getCallersIncs');
incGA.addParam('sysparm_callerID', g_form.getValue('caller_id'));
incGA.getXMLAnswer(CallerIncidentsParse);

function CallerIncidentsParse(response) {
  //Build an array of objects from the JSON object and take action
  var myObj = JSON.parse(response);
  g_form.addInfoMessage('User has raised the following incidents:');

  for (var i = 0; i < myObj.length; i++) {
    g_form.addInfoMessage(myObj[i].number + ': ' + myObj[i].shortDesc);
  }
}
11

Navigation & Debugging

URL shortcuts

/incident_list.do?sysparm_query=active=true
/incident.do?sys_id=-1              new record
/sys.scripts.do                     background scripts
/sys_properties_list.do             all properties
/syslog_list.do                     platform logs
/stats.do                           instance stats
/cache.do                           flush the cache
/nav_to.do?uri=incident_list.do

All Menu Navigation

incident.do                  new form 
incident.list                list records
incident.config              configs for table
stats.do                     instance stats
cache.do                     flush the cache