Developer Reference

ServiceNow Code Recipes

Copy-paste solutions for common ServiceNow scripting tasks

Server-sideintermediate

Sum a numeric field across records

Calculate the total sum of a numeric field across all matching records

View recipe →
Server-sideadvanced

Detect an impersonated session

Detect whether the current session is impersonating another user

View recipe →
Server-sidebeginner

Prevent a record from saving with a Business Rule message

Block a record from being saved and show the user an error message

View recipe →
Server-sideintermediate

Query incidents using addQuery with IN operator

Filter records where a field matches any value in a list

View recipe →
Server-sideintermediate

Create a system event with gs.eventQueue

Fire a custom event using gs.eventQueue to trigger downstream notifications or script actions

View recipe →
Server-sidebeginner

Update a field on the current record in a Business Rule

Modify a field value on the triggering record in a Before Business Rule

View recipe →
Server + Clientadvanced

Return multiple values from a GlideAjax call

Return a JSON object with multiple fields from a single GlideAjax server call

View recipe →
Server-sidebeginner

Check if a record exists without iterating

Determine whether a matching record exists using hasNext()

View recipe →
Client-sidebeginner

Make a field mandatory dynamically in a Client Script

Dynamically set a field as mandatory or optional based on another field's value

View recipe →
Server-sidebeginner

Query incidents by assignment group

Get all open incidents assigned to a specific group

View recipe →
Client-sidebeginner

Get the current record sys_id in a Client Script

Retrieve the sys_id of the record currently open in the form

View recipe →
Server-sideintermediate

Avoid querying the database inside a loop

Batch database lookups instead of querying once per iteration

View recipe →
Server-sideintermediate

Get the active SLA on a task record

Query the task_sla table to find the active SLA attached to a specific task

View recipe →
Server-sideadvanced

Create a Scripted REST API endpoint

Define a custom REST API endpoint that returns JSON data

View recipe →
Server-sidebeginner

Look up a user record by sys_id in a Script Include

Fetch a sys_user record by sys_id and return key fields as an object

View recipe →
Client-sideintermediate

Set a field value using g_form in a UI Action

Update a form field value from a UI Action client script

View recipe →
Server-sideintermediate

Query incidents created in the last 7 days

Retrieve incidents created within the past 7 days

View recipe →
Client-sidebeginner

Run onChange logic only when the field actually changes

Execute logic only when a field value changes, skipping form load

View recipe →
Server-sidebeginner

Create a class-based Script Include

Define a reusable server-side library using the class-based Script Include pattern

View recipe →
Server-sidebeginner

Get a single record by sys_id

Retrieve a single record directly by its sys_id

View recipe →
Server-sideintermediate

Copy a record in GlideRecord

Duplicate an existing record by copying all its field values to a new record

View recipe →
Client-sideintermediate

Trigger client-side validation in onSubmit

Validate form fields before submission and block save if validation fails

View recipe →
Server-sideintermediate

Parse a JSON response from a REST call

Extract fields from a JSON API response in a server-side script

View recipe →
Server + Clientintermediate

Avoid GlideRecord calls in client-side scripts

Replace a synchronous client-side GlideRecord call with GlideAjax

View recipe →
Server-sidebeginner

Insert a new record with GlideRecord

Create a new database record programmatically

View recipe →
Server-sidebeginner

Get the parent request from an RITM

Navigate from a Requested Item record up to its parent Request record

View recipe →
Server-sideintermediate

Make an outbound REST call with Basic Auth

Call an external REST endpoint using Basic authentication

View recipe →
Server-sideintermediate

Get a catalog variable value from an RITM

Read the value of a catalog variable from a Requested Item record

View recipe →
Server-sideadvanced

Read the request body in a Scripted REST endpoint

Parse the JSON request body in an inbound Scripted REST API endpoint

View recipe →
Server-sidebeginner

Auto-populate a field based on another field in a Business Rule

Auto-fill a field value based on what the user enters in a related field

View recipe →
Server-sidebeginner

Check if the current user has a role

Determine whether the current user holds a specific security role

View recipe →
Server + Clientintermediate

Reload a form after a server-side UI Action completes

Force the form to refresh after a server-side UI Action makes changes

View recipe →
Client-sidebeginner

Set a field value in a Client Script

Programmatically set the value of a form field from a Client Script

View recipe →
Server-sidebeginner

Get the display value of a reference field

Read the display label of a reference field rather than its sys_id

View recipe →
Server-sideintermediate

Get all RITMs from a service catalog request

Query all Requested Items that belong to a parent Request record

View recipe →
Server-sideintermediate

Query with OR conditions using addOrCondition

Query records matching one of several values using OR logic

View recipe →
Server-sideintermediate

Format a datetime for display in the user's timezone

Convert a stored UTC datetime to a human-readable string in the user's local timezone

View recipe →
Server-sideintermediate

Use addQuery with STARTSWITH and CONTAINS operators

Filter text fields with partial match operators like STARTSWITH and CONTAINS

View recipe →
Server-sideadvanced

Get value from a transform script in an import set

Use a transform script to set a target field value based on source data

View recipe →
Server-sideintermediate

Query child table records using the parent table

Query a table that extends another and work with both parent and child fields

View recipe →
Client-sideintermediate

Check if the current user has a role in a Client Script

Determine if the current user holds a specific role from a Client Script

View recipe →
Server-sidebeginner

Query incidents by caller

Retrieve all incidents raised by a specific user

View recipe →
Server-sideadvanced

Get a field's internal name from a GlideRecord

Iterate over all fields on a record to get their internal column names

View recipe →
Server-sideadvanced

Process records in batches to avoid scheduled job timeout

Handle large record sets in a scheduled job using batch processing

View recipe →
Client-sidebeginner

Hide and show a form section

Show or hide an entire form section based on a field value

View recipe →
Server-sidebeginner

Query all active incidents using GlideRecord

Retrieve all active incident records

View recipe →
Server-sideintermediate

Dot-walk to a referenced field in GlideRecord

Access a field on a referenced record without a second GlideRecord query

View recipe →
Server-sidebeginner

Log a message to the system log

Write a debug, info, warn, or error message to the ServiceNow system log

View recipe →
Server-sidebeginner

Update multiple records in a GlideRecord loop

Loop through records and update each one

View recipe →
Server-sideintermediate

Count records matching a condition with GlideAggregate

Count how many records match a query without loading all rows

View recipe →
Server-sidebeginner

Query incidents by state value

Filter incidents by a specific state value such as In Progress

View recipe →
Server-sideintermediate

Count records using GlideRecord vs GlideAggregate

Understand when to use getRowCount vs GlideAggregate COUNT for performance

View recipe →
Client-sidebeginner

Make a field read-only in a Client Script

Prevent users from editing a specific field without hiding it

View recipe →
Server-sideintermediate

Delete a record with GlideRecord

Delete a specific record by sys_id

View recipe →
Server-sideintermediate

Add a user to a group programmatically

Insert a user into a sys_user_group via a server-side script

View recipe →
Server-sidebeginner

Find a CI by name or IP address

Look up a Configuration Item by its name or IP address

View recipe →
Server-sideintermediate

Use getRefRecord to access a reference field record

Retrieve the full GlideRecord for a reference field without a second query

View recipe →
Server-sideintermediate

Check the approval status of a catalog request

Query the approval state of a service catalog request from a Business Rule

View recipe →
Client-sidebeginner

Prevent form submission with a validation message

Block a form from being submitted when validation fails

View recipe →
Server-sidebeginner

Trigger Business Rule logic only when a specific field changes

Run logic only when a targeted field value has changed

View recipe →
Server + Clientintermediate

Populate a reference field using a server-side GlideAjax lookup

Auto-fill a reference field based on another field's value using a server lookup

View recipe →
Server-sideintermediate

Query records in a date range

Retrieve records created or updated within a specific date range

View recipe →
Server-sidebeginner

Get all users in a group

Retrieve all members of a specific sys_user_group

View recipe →
Client-sideintermediate

Set a reference field with display value

Set a reference field to a sys_id while showing the correct display label

View recipe →
Server-sideintermediate

Query all CIs linked to an incident

Retrieve all Configuration Items associated with an incident record

View recipe →
Server-sideintermediate

Get all relationships for a CI

Retrieve all parent and child CI relationships from the CMDB

View recipe →
Server-sideintermediate

Get all roles assigned to a user

Retrieve all roles held by a user including group-inherited roles

View recipe →
Server + Clientintermediate

Make a basic GlideAjax call from a Client Script

Call a server-side Script Include method from a Client Script using GlideAjax

View recipe →
Server-sidebeginner

Add days to a date

Calculate a future or past date by adding or subtracting a number of days

View recipe →
Server-sideintermediate

Calculate the number of days between two dates

Find the number of days elapsed between two date-time values

View recipe →
Server-sidebeginner

Read a display value vs stored value from a choice field

Get both the stored integer value and the display label of a choice field

View recipe →
Server + Clientintermediate

Get a user's manager via GlideAjax

Retrieve the current user's manager from the server and populate a reference field

View recipe →
Server-sideadvanced

Create a text attachment on a record

Programmatically attach a generated text file to a record

View recipe →
Server-sideintermediate

Query using addNullQuery and addNotNullQuery

Filter records where a field is empty or where it has any value

View recipe →
Server-sideintermediate

Get all attachments for a record

Retrieve all files attached to a specific record

View recipe →
Server-sidebeginner

Compare two GlideDateTime values

Determine which of two dates is earlier, later, or if they are equal

View recipe →
Server-sidebeginner

Get the current user's sys_id

Retrieve the sys_id of the currently logged-in user

View recipe →
Server-sidebeginner

Order GlideRecord query results

Sort GlideRecord results by a field ascending or descending

View recipe →
Server-sideadvanced

Copy attachments from one record to another

Duplicate all attachments from a source record to a target record

View recipe →
Server-sidebeginner

Limit GlideRecord query results

Limit a GlideRecord query to a specific number of rows

View recipe →
Server-sidebeginner

Get the current user's name and email

Retrieve the full name and email address of the currently logged-in user

View recipe →
Server-sideintermediate

Check if the current user is in a group

Determine whether the current user is a member of a specific group

View recipe →
Client-sidebeginner

Flash a field to draw attention

Briefly highlight a form field to draw the user's attention to it

View recipe →
Server-sidebeginner

Get a user's manager sys_id

Retrieve the manager reference for a specific user record

View recipe →
Server-sidebeginner

Null check a reference field in GlideRecord

Safely check whether a reference field is populated before accessing it

View recipe →
Client-sideintermediate

Get the previous value of a field in onChange

Read the field's value before the user changed it in an onChange Client Script

View recipe →
Client-sidebeginner

Display a message under a field

Show an informational or error message under a specific form field

View recipe →
Server-sideintermediate

Access the triggering record in a Flow Designer script step

Read and update the record that triggered a flow from within a script step

View recipe →
Server-sideintermediate

Get choice field options dynamically

Retrieve all available options for a choice field at runtime

View recipe →
Server-sideintermediate

Return a result object from a Script Include

Return structured success/failure data from a Script Include method

View recipe →
Server-sidebeginner

Read a system property value

Read a ServiceNow system property by its key name

View recipe →
Server-sidebeginner

Call a Script Include from a Business Rule

Invoke a Script Include function from within a Business Rule

View recipe →
Server-sideintermediate

Set a catalog variable value in a Business Rule

Programmatically set the value of a catalog variable on an RITM

View recipe →
Server-sidebeginner

Get the current date and time

Retrieve the current date and time as a GlideDateTime object

View recipe →
Server-sideintermediate

Query records using an encoded query string

Run a GlideRecord query using a pre-built encoded query string

View recipe →
Server-sideintermediate

Count incidents grouped by state

Get a count of incidents grouped by each state value

View recipe →
Server-sideadvanced

Paginate through large result sets with GlideRecord

Process large query results in chunks using chooseWindow to avoid timeouts

View recipe →
Server-sidebeginner

Get the sys_id of a record inserted with GlideRecord

Capture the sys_id of a newly created record after insertion

View recipe →
Client-sidebeginner

Hide and show a field in a Client Script

Programmatically show or hide a form field based on another field's value

View recipe →
Server-sideintermediate

Set a workflow scratchpad variable

Write a value to the workflow scratchpad from a Run Script activity

View recipe →
Client-sidebeginner

Check if the form is in insert mode or edit mode

Determine whether the form is creating a new record or editing an existing one

View recipe →
Server-sideintermediate

Make an outbound REST call with RESTMessageV2

Send an HTTP GET request to an external API and parse the JSON response

View recipe →
Server-sideintermediate

Send a notification from an async Business Rule

Trigger an email notification from a Business Rule when a condition is met

View recipe →
Server-sideadvanced

Set the current update set via script

Switch the active update set programmatically in a background script

View recipe →
Client-sideintermediate

Use g_form.getReference to get a reference record client-side

Fetch fields from a referenced record without a GlideAjax call using g_form.getReference

View recipe →
Server-sideintermediate

Write a scheduled background script

Create a well-structured scheduled job script that runs on a recurring schedule

View recipe →
Client-sidebeginner

Get a field value in a Client Script

Read the current value of a form field from a Client Script

View recipe →