Understanding Glide API in ServiceNow: A Comprehensive Guide

Mastering ServiceNow: Your Essential Guide to Glide APIs

Hey there, fellow ServiceNow enthusiast! Ever wondered how to truly make ServiceNow dance to your tune, beyond just configuring forms and workflows? The secret sauce, my friend, often lies within the powerful world of Glide APIs. If you’re a developer, administrator, or just someone looking to supercharge your ServiceNow instance, understanding these APIs is not just helpful; it’s absolutely essential.

In this comprehensive article, we’re going to unravel the mysteries of Glide APIs. Think of this as your friendly, in-depth chat about scripting in ServiceNow, peppered with practical advice, real-world scenarios, and maybe even a few tips that’ll make you shine in your next interview. Let’s dive in!

Glide API Overview: The Heartbeat of ServiceNow Customization

At its core, ServiceNow is a platform designed for incredible flexibility. While you can achieve a lot through configuration, the real magic happens when you start scripting. This is where Glide APIs come into play. They are a set of JavaScript classes and methods provided by ServiceNow that allow developers to interact with the platform’s underlying data, UI, and system processes programmatically.

Why do we use them? Simple: to change default behaviors, customize existing functionalities, automate tasks, and perform database operations without having to write a single SQL query. Yes, you heard that right – no direct SQL! ServiceNow abstracts that complexity away, giving us robust, secure, and platform-optimized ways to get things done.

Each Glide API (or “Glide Class”) is a specialized toolkit, packed with methods designed for specific purposes. For instance, one might be for database interactions, another for manipulating forms on the client-side, and yet another for gathering information about the logged-in user.

Client-Side vs. Server-Side: A Crucial Distinction

One of the first things you’ll learn about Glide APIs is whether they operate on the client-side or the server-side. This isn’t just a technical detail; it dictates where and how you can use them:

  • Client-Side APIs: These run directly in the user’s web browser. They’re perfect for manipulating forms, displaying messages, and interacting with the user interface in real-time. Think of things happening instantly without a page refresh.
  • Server-Side APIs: These execute on the ServiceNow server. They’re your go-to for database operations (CRUD), system-level interactions, user management, and anything that requires access to the full platform capabilities.

Here’s a quick glance at some of the most common Glide APIs we’ll be exploring:

  • Server-Side: GlideRecord, GlideSystem, GlideDate, GlideDateTime, GlideAggregation, GlideSession
  • Client-Side: GlideForm, GlideUser, GlideAjax, GlideDialogWindow, GlideList

Understanding GlideRecord: Your Database Powerhouse

Overview and Usage of GlideRecord

If you’re going to do anything significant with data in ServiceNow, GlideRecord is your best friend. It’s hands down the most common and vital API for server-side scripting. Essentially, GlideRecord is a native JavaScript class that acts as an abstraction layer for database operations. It allows you to perform CRUD (Create, Read, Update, Delete) operations on any table in your ServiceNow instance, all without writing a single line of SQL.

Think of it as a cursor that can traverse rows and columns in a database table. You “point” it to a table, define your query conditions, and then iterate through the results or manipulate individual records. Since direct database interaction via SQL queries is restricted in ServiceNow (for good reasons like security and platform integrity), GlideRecord becomes your primary tool for programmatic data management.

Important Note: Always, always, ALWAYS test your GlideRecord scripts on a non-production instance first! An incorrectly constructed query or update, especially with methods like deleteMultiple(), can lead to severe data loss. Don’t learn this the hard way! This is a frequent interview question, emphasizing best practices.

Key GlideRecord Methods and Practical Examples

Let’s look at some of the most frequently used methods:

Instantiation and Querying

To start, you need to instantiate a GlideRecord object, specifying the table you want to interact with:


var gr = new GlideRecord('incident'); // 'incident' is the table name
    

Then, you add your query conditions:

  • addQuery(fieldName, value): Adds a simple equality condition.
  • addQuery(fieldName, operator, value): Adds a condition with a specific operator (e.g., ‘>’, ‘<‘, ‘CONTAINS’).
  • addEncodedQuery(encodedQueryString): Allows you to use an encoded query string (which you can generate from list filters) for complex conditions. This is super powerful!
  • addActiveQuery() / addInactiveQuery(): Handy shortcuts to filter for active or inactive records.
  • query(): Executes the query.
  • next(): Moves the cursor to the next record in the result set. Typically used in a while loop.

// Exercise 1: Display all active, high-priority incidents in the software category
var inc = new GlideRecord('incident');
inc.addActiveQuery(); // active=true
inc.addQuery('priority', 1); // priority=1
inc.addQuery('category', 'software'); // category=software
inc.query(); // Execute the query

gs.info('--- High-Priority Software Incidents ---');
while (inc.next()) { // Loop through results
    gs.info('Incident Number: ' + inc.number + ', Short Description: ' + inc.short_description);
}

// Exercise 2: Using an encoded query
var encodedQuery = 'active=true^category=hardware^priorityIN1,2'; // Active, hardware, priority 1 or 2
var hwInc = new GlideRecord('incident');
hwInc.addEncodedQuery(encodedQuery);
hwInc.query();

gs.info('\n--- Active Hardware Incidents (Priority 1 or 2) ---');
while (hwInc.next()) {
    gs.info('Incident: ' + hwInc.number + ' - ' + hwInc.getValue('short_description'));
}
    

Retrieving and Setting Values

  • getValue(fieldName): Gets the actual database value of a field.
  • getDisplayValue(fieldName): Gets the display value of a field (e.g., “High” instead of “1” for priority).
  • setValue(fieldName, value): Sets the value of a field.
  • You can also directly access fields as properties: inc.short_description.

// Exercise 3: Get and set a field value
var inc = new GlideRecord('incident');
if (inc.get('INC0000001')) { // Get a specific record by its number
    gs.info('Original Category for ' + inc.number + ': ' + inc.category.getDisplayValue());
    inc.setValue('category', 'network'); // Set the category to 'network'
    inc.update(); // Save the changes
    gs.info('Updated Category for ' + inc.number + ': ' + inc.category.getDisplayValue());
} else {
    gs.info('Incident INC0000001 not found.');
}
    

Creating, Updating, and Deleting Records

  • initialize(): Creates a new, empty GlideRecord object, ready to be populated.
  • insert(): Inserts the new record into the database.
  • update(): Updates the current record with the changes you’ve made.
  • deleteRecord(): Deletes the current record.
  • deleteMultiple(): Deletes all records matching the current query. Use with extreme caution!
  • updateMultiple(): Updates all records matching the current query.

// Exercise 4: Create a new incident
var newInc = new GlideRecord('incident');
newInc.initialize(); // Initialize a new record
newInc.category = 'network';
newInc.short_description = 'New Network Issue Reported via Script';
newInc.priority = 1;
newInc.insert(); // Insert into the database
gs.info('Created new incident: ' + newInc.number);

// Exercise 5: Update multiple records
var incidentsToUpdate = new GlideRecord('incident');
incidentsToUpdate.addQuery('state', 1); // Where state is 'New'
incidentsToUpdate.addQuery('category', 'software'); // And category is 'software'
incidentsToUpdate.setValue('state', 6); // Set state to 'Resolved'
incidentsToUpdate.updateMultiple(); // Update all matching records
gs.info('Updated multiple software incidents from New to Resolved.');
    

Other Useful Methods

  • get(sys_id) or get(fieldName, value): Retrieves a single record directly.
  • getRowCount(): Returns the number of records in the current query result.
  • orderBy(fieldName) / orderByDesc(fieldName): Sorts the results.
  • setLimit(count): Limits the number of records returned.
  • isValidRecord(): Checks if the current GlideRecord object represents an actual record in the database.
  • autoSysFields(false): Prevents system fields (like sys_updated_on) from updating. Handy for data migration scripts.
  • setWorkflow(false): Prevents business rules from running. Again, use with care!

Interview Relevance: GlideRecord is a common topic. Expect questions on CRUD operations, client-side vs. server-side context, addQuery vs. addEncodedQuery, and the dangers of deleteMultiple.

GlideForm (g_form): Client-Side Form Interaction

Overview and Usage of GlideForm

When you need to manipulate elements on a form directly from the user’s browser, GlideForm (g_form) is your tool. This is a client-side API, meaning its methods run within client scripts (and UI policies that execute scripts). It allows you to dynamically change form fields, add messages, manage UI elements, and enforce client-side validations.

Think of g_form as your direct command console for the form currently displayed on the user’s screen. You can make fields mandatory, hide them, set their values, or even add informative messages to guide the user.

Tip: While you can do a lot with g_form, always consider if a UI Policy or Client Script with less JavaScript is a better, more maintainable approach for simple form changes.

Key GlideForm Methods and Practical Examples

To use g_form, you’ll typically write a Client Script and execute it. For quick testing, you can use your browser’s developer console (F12 or Ctrl+Shift+J/Cmd+Option+J in most browsers) while on a ServiceNow form.

Field Manipulation

  • getValue(fieldName): Retrieves the current value of a field on the form.
  • setValue(fieldName, value): Sets the value of a field.
  • setMandatory(fieldName, boolean): Makes a field mandatory or optional.
  • setDisplay(fieldName, boolean): Hides or shows a field, often collapsing the space it occupied.
  • setVisible(fieldName, boolean): Similar to setDisplay, but typically maintains the space the field would occupy.
  • setReadOnly(fieldName, boolean): Makes a field read-only.

// Exercise 1: Make Short Description mandatory and set Category
// (Run this in the browser's JavaScript console on an Incident form)
alert('Current Category: ' + g_form.getValue('category'));
g_form.setMandatory('short_description', true);
g_form.setValue('category', 'software');
g_form.addInfoMessage('Short Description is now mandatory and category set to Software.');
    

Messages and Attachments

  • addInfoMessage(message): Displays an informational message at the top of the form.
  • addErrorMessage(message): Displays an error message.
  • clearMessages(): Clears all messages.
  • showFieldMsg(fieldName, message, type): Displays a message directly under a specific field. type can be ‘info’, ‘error’, ‘warning’.
  • hideFieldMsg(fieldName, clearAll): Hides a field message.
  • disableAttachments() / enableAttachments(): Controls the attachment icon.

// Exercise 2: Display messages and manage attachments
g_form.addErrorMessage('Please review the errors below!');
g_form.showFieldMsg('impact', 'Impact needs your attention!', 'error');
g_form.disableAttachments(); // Hide the paperclip icon
    

Choices and Other Interactions

  • addOption(fieldName, value, label): Adds a new choice to a choice list.
  • removeOption(fieldName, value): Removes a choice from a choice list.
  • clearOptions(fieldName): Removes all choices from a field.
  • isNewRecord(): Returns true if the record is new (not yet saved).
  • getTableName(): Returns the name of the current table.
  • getUniqueValue(): Returns the sys_id of the current record.

Interview Relevance: Client scripts and UI policies are foundational. Knowing g_form methods for validation, display, and setting values is key. They might ask about performance considerations for client scripts.

GlideUser (g_user & gs.getUser()): Who’s Logged In?

Overview and Usage of GlideUser

The GlideUser API is all about getting information about the currently logged-in user. It’s incredibly useful for personalizing user experiences, checking roles, and tailoring application behavior based on who is interacting with the system.

Interestingly, GlideUser has two flavors depending on where you’re scripting:

  • Client-Side (g_user): Available in Client Scripts and UI Actions that run on the client. It provides quick access to basic user details and roles in the browser.
  • Server-Side (gs.getUser()): Accessed via gs.getUser() in server-side scripts (Business Rules, Script Includes, Workflows). This provides more comprehensive user information directly from the server.

Key GlideUser Methods and Practical Examples (Client-Side: g_user)

These methods are quick and efficient for client-side checks.

  • firstName / lastName / fullName: Get parts or the full name of the user.
  • userName: Gets the user’s login ID.
  • userID: Gets the 32-digit sys_id of the user.
  • hasRole(roleName): Checks if the user has a specific role (including inherited roles).
  • hasRoleExactly(roleName): Checks if the user has the role assigned directly (not inherited).
  • hasRoleFromList(roleList): Checks if the user has any role from a comma-separated list.

// Exercise 1: Get current user details (Client-side via browser console)
alert('Welcome, ' + g_user.firstName + ' ' + g_user.lastName + '!');
alert('Your User ID: ' + g_user.userID);

if (g_user.hasRole('admin')) {
    alert('You are an admin!');
} else {
    alert('You are not an admin.');
}
    

Key GlideUser Methods and Practical Examples (Server-Side: gs.getUser())

When running in a Business Rule or Script Include, use gs.getUser().

  • getFirstName() / getLastName() / getFullName(): Get the user’s name details.
  • getEmail(): Gets the user’s email address.
  • getID(): Gets the 32-digit sys_id.
  • getName(): Gets the user’s login ID.
  • hasRole(roleName): Same functionality as client-side hasRole.
  • isMemberOf(groupName): Checks if the user is a member of a specific group.
  • getRoles(): Returns a comma-separated string of all roles the user has.

// Exercise 2: Server-side user details (Run in Scripts - Background)
var currentUser = gs.getUser();
gs.print('Server-side user: ' + currentUser.getFullName() + ' (' + currentUser.getName() + ')');
gs.print('Email: ' + currentUser.getEmail());

if (currentUser.isMemberOf('Service Desk')) {
    gs.print('This user is part of the Service Desk group.');
}

// Example of checking for a specific user by ID
var abelTuter = gs.getUser().getUserByID('abel.tuter');
if (abelTuter) {
    gs.print('Abel Tuter\'s first name: ' + abelTuter.getFirstName());
}
    

Troubleshooting: Remember that g_user (client-side) only knows about roles at the time of session creation. If a user’s roles change during a session, g_user might not reflect it until the user logs out and logs back in. gs.getUser() (server-side) will reflect current roles more accurately.

Interview Relevance: Distinguishing between client-side g_user and server-side gs.getUser() is a classic. Be prepared to explain when to use each.

GlideSystem (gs): Your Server-Side System Utility Belt

Overview and Usage of GlideSystem

GlideSystem (gs) is a powerful server-side API that provides a wealth of utility methods for interacting with the ServiceNow system itself. It’s your Swiss Army knife for server-side scripting, offering functionalities like logging messages, managing session information, getting system properties, and working with dates and times.

You’ll encounter gs everywhere in server-side scripts: Business Rules, Script Includes, UI Actions (server-side), Scheduled Jobs, and Fix Scripts. It’s the global object that allows your scripts to communicate with the core platform features.

Key GlideSystem Methods and Practical Examples

Messaging and Logging

  • addInfoMessage(message) / addErrorMessage(message): Displays messages to the user in the current session (similar to client-side, but from the server).
  • info(message) / warn(message) / error(message): Logs messages to the system log (useful for debugging and auditing).
  • print(message): Prints output to the console, especially useful in Scripts – Background or Fix Scripts.

// Exercise 1: Logging messages (Run in Scripts - Background)
gs.info('This is an informational message from GlideSystem.');
gs.warn('Watch out, something might be slightly off here.');
gs.error('Oh no! A critical error occurred!');
gs.print('This output will show directly in the script runner.');
    

User and Session Information (Overlap with GlideUser)

  • getUser(): Returns a GlideUser object (as discussed above).
  • getUserDisplayName() / getUserID() / getUserName(): Direct access to current user’s display name, sys_id, and login name.
  • hasRole(roleName): Checks if the current user has a role.
  • isInteractive(): Determines if the current session is an interactive user session (vs. a SOAP/REST call).

// Exercise 2: Session and user details
gs.print('Current interactive session: ' + gs.isInteractive());
gs.print('Current user display name: ' + gs.getUserDisplayName());
    

Date and Time Utilities

gs offers many convenient methods for common date/time calculations, often used in encoded queries:

  • beginningOfToday() / endOfToday(): Gets the start/end of the current day in GMT.
  • daysAgo(X) / daysAgoStart(X) / daysAgoEnd(X): Calculates dates X days ago.
  • now() / nowDateTime(): Gets the current date/time in various formats.
  • Many more for weeks, months, quarters, and years (e.g., beginningOfLastMonth()).

// Exercise 3: Date calculations for queries
var queryDate = gs.daysAgo(7); // Date 7 days ago
gs.print('Seven days ago: ' + queryDate);

// Example of using in a GlideRecord query
var recentInc = new GlideRecord('incident');
recentInc.addQuery('opened_at', '>=', gs.daysAgo(7));
recentInc.query();
gs.print('Incidents opened in the last 7 days: ' + recentInc.getRowCount());
    

System Properties and Other Utilities

  • getProperty(propertyName): Retrieves the value of a system property.
  • setProperty(propertyName, value): Sets a system property (use with caution in production!).
  • getMessage(messageKey): Retrieves a translated message from the sys_ui_message table.

Troubleshooting: For debugging server-side scripts, gs.info(), gs.warn(), and gs.error() are your best friends. Check the System Log (syslog.do) frequently!

Interview Relevance: How to log messages, retrieve system properties, and differentiate between client-side and server-side messaging are common interview questions.

GlideSession: Managing User Sessions

Overview and Usage of GlideSession

The GlideSession API (accessed via gs.getSession() on the server-side) allows you to get and set information related to the current user’s session. It’s particularly useful for maintaining state or passing data between server-side and client-side scripts within the context of a single user session.

While less frequently used than GlideRecord or GlideSystem, it offers unique capabilities for dynamic, session-specific interactions.

Key GlideSession Methods and Practical Examples

  • getClientData(key): Retrieves a client-side session value previously set by putClientData().
  • putClientData(key, value): Sets a client-side session value that can be retrieved by client scripts.
  • getLanguage(): Gets the session’s language code.
  • getTimeZoneName(): Gets the name of the session’s time zone.
  • isLoggedIn() / isInteractive(): Checks login status and interactivity (similar to gs methods).

// Exercise 1: Passing data between server and client (server-side script)
// This would run in a Business Rule for example
var session = gs.getSession();
session.putClientData('userPreference', 'darkTheme');
gs.info('Session data "userPreference" set to darkTheme.');

// On the client-side (Client Script):
// var userPref = g_user.getClientData('userPreference'); // g_user also has getClientData
// if (userPref === 'darkTheme') { /* apply dark theme logic */ }
    

// Exercise 2: Get session details (Scripts - Background)
var session = gs.getSession();
gs.print('Session Language: ' + session.getLanguage());
gs.print('Session Time Zone: ' + session.getTimeZoneName());
gs.print('User logged in: ' + session.isLoggedIn());
    

Interview Relevance: putClientData and getClientData are good to know for scenarios where you need to send server-side data to the client that isn’t directly on the form.

GlideDate & GlideDateTime: Precision with Dates and Times

Overview and Usage of GlideDate & GlideDateTime

Working with dates and times in any development platform can be tricky, and ServiceNow is no exception. That’s where GlideDate and GlideDateTime classes come in. They provide robust objects and methods for creating, manipulating, and comparing dates and times, handling time zones, and formatting.

  • GlideDate: For date-only values (yyyy-MM-dd).
  • GlideDateTime: For date and time values (yyyy-MM-dd HH:mm:ss).

These are server-side APIs and are crucial for calculations, setting field values, and filtering queries based on time-sensitive criteria.

Key GlideDate & GlideDateTime Methods and Practical Examples

Instantiation and Basic Retrieval


// Exercise 1: Instantiation and basic values (Scripts - Background)
var today = new GlideDate();
gs.print('Current Date (GMT): ' + today.getValue()); // e.g., 2023-10-27

var now = new GlideDateTime();
gs.print('Current DateTime (GMT): ' + now.getValue()); // e.g., 2023-10-27 10:30:00

gs.print('Display Value (user TZ): ' + now.getDisplayValue()); // e.g., 10/27/2023 06:30:00 AM PST
    

Manipulation and Calculation

  • addDays(X) / addMonths(X) / addYears(X) / addSeconds(X): Adds or subtracts time units.
  • subtract(otherGlideDate/Time): Calculates the duration difference between two objects.

// Exercise 2: Date/Time Calculations
var futureDate = new GlideDate();
futureDate.addDays(10);
gs.print('Date 10 days from now: ' + futureDate.getValue());

var futureDateTime = new GlideDateTime();
futureDateTime.addMonths(2);
futureDateTime.addSeconds(3600); // Add 1 hour
gs.print('DateTime 2 months and 1 hour from now: ' + futureDateTime.getValue());

var dt1 = new GlideDateTime('2023-10-20 09:00:00');
var dt2 = new GlideDateTime('2023-10-21 10:30:00');
var duration = GlideDateTime.subtract(dt1, dt2); // Note: static method for difference
gs.print('Difference between dates: ' + duration.getDisplayValue()); // e.g., 1 Day 1 Hour 30 Minutes
    

Getting Specific Components and Comparisons

  • getDayOfMonth() / getMonth() / getYear(): Get specific parts of the date. (Use ...LocalTime() or ...UTC() variants for clarity).
  • compareTo(otherGlideDateTime): Compares two GlideDateTime objects. Returns 0 if equal, 1 if current is after, -1 if current is before.
  • isValid(): Checks if the GlideDateTime object holds a valid date/time.

Troubleshooting: Always be mindful of time zones! Methods ending in NoTZ, UTC, or LocalTime specify the time zone context. When working with user-facing dates, getDisplayValue() and setDisplayValue() are your friends for respecting the user’s time zone settings.

Interview Relevance: Expect questions on handling time zones, calculating durations, and formatting dates for display or database storage.

GlideAggregate: Summarize Your Data Like a Pro

Overview and Usage of GlideAggregate

When you don’t need individual records but rather statistical summaries of your data, GlideAggregate is your go-to server-side API. It’s an extension of GlideRecord but is specifically designed for database aggregation queries. Think of it as performing SQL functions like COUNT(), SUM(), MIN(), MAX(), and AVG() directly within your ServiceNow scripts.

This API is incredibly powerful for custom reports, dashboards, or calculating values for performance indicators. It primarily works with numeric fields.

Key GlideAggregate Methods and Practical Examples

  • addAggregate(function, fieldName): Specifies the aggregation function (e.g., ‘COUNT’, ‘SUM’, ‘AVG’) and the field to apply it to.
  • groupBy(fieldName): Groups the aggregation results by a specific field, similar to SQL’s GROUP BY.
  • query(): Executes the query.
  • getAggregate(function, fieldName): Retrieves the aggregated value.

// Exercise 1: Count active incidents by category (Scripts - Background)
var ga = new GlideAggregate('incident');
ga.addQuery('active', true);
ga.addAggregate('COUNT', 'category'); // Count incidents grouped by category
ga.groupBy('category');
ga.query();

gs.info('--- Active Incident Counts by Category ---');
while (ga.next()) {
    var category = ga.category.getDisplayValue(); // Get the display value for the category
    var count = ga.getAggregate('COUNT', 'category');
    gs.print('Category: ' + category + ' - Count: ' + count);
}
    

// Exercise 2: Average and Max for a numeric field
var gaAvg = new GlideAggregate('incident');
gaAvg.addQuery('active', true);
gaAvg.addAggregate('AVG', 'sys_mod_count'); // Average number of modifications
gaAvg.addAggregate('MAX', 'sys_mod_count'); // Max number of modifications
gaAvg.groupBy('category');
gaAvg.query();

gs.info('\n--- Average & Max Modifications by Category ---');
while (gaAvg.next()) {
    var category = gaAvg.category.getDisplayValue();
    var avgMods = gaAvg.getAggregate('AVG', 'sys_mod_count');
    var maxMods = gaAvg.getAggregate('MAX', 'sys_mod_count');
    gs.print('Category: ' + category + ' - Avg Mods: ' + avgMods + ', Max Mods: ' + maxMods);
}
    

Troubleshooting: Ensure the field you’re aggregating (e.g., for SUM, AVG) is actually a numeric field. Aggregating text fields will often yield unexpected or zero results.

Interview Relevance: This is a more advanced topic, but knowing GlideAggregate demonstrates a deeper understanding of data manipulation in ServiceNow, especially for reporting needs.

Client Scripts, Business Rules, and API Context

It’s essential to understand where you’ll actually be writing and executing these Glide API calls:

Client Scripts

Client Scripts (sys_script_client) execute on the browser and are where you’ll primarily use g_form, g_user, and GlideAjax. GlideAjax is a special client-side API that allows you to make asynchronous calls to the server without refreshing the page, enabling dynamic data retrieval or server-side processing from the client.


// Example: Client Script + GlideAjax (simplified)
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    // Assume you want to fetch user's company details from server
    var ga = new GlideAjax('MyScriptInclude'); // Name of your Script Include
    ga.addParam('sysparm_name', 'getCompanyInfo'); // Method in Script Include
    ga.addParam('sysparm_user_id', newValue); // Pass current user's sys_id
    ga.getXML(myCompanyInfoCallback); // Execute and call callback function

    function myCompanyInfoCallback(response) {
        var answer = response.responseXML.documentElement.getAttribute('answer');
        // Do something with the answer on the form
        g_form.addInfoMessage('User is from company: ' + answer);
    }
}
    

Business Rules

Business Rules (sys_script) run on the server and are the most common place for GlideRecord, gs, gs.getUser(), and the Glide Date/Time APIs. They trigger before or after a record is displayed, inserted, updated, or deleted. Business Rules also offer access to the current and previous objects, representing the record’s current and prior states, respectively.

For display Business Rules, you also have access to g_scratchpad, which is an empty object passed from the server to the client. This is a secure and efficient way to send server-side data to your client scripts without modifying the form.


// Example: Business Rule with g_scratchpad (server-side)
// (This would be in a "Display" type Business Rule)
g_scratchpad.isAdmin = gs.hasRole('admin');
g_scratchpad.callerEmail = current.caller_id.email; // Assuming current is an incident record

// In a client script for the same form, you could then access:
// if (g_scratchpad.isAdmin) { /* do something for admins */ }
// alert('Caller email: ' + g_scratchpad.callerEmail);
    

A Few Troubleshooting Tips for Glide APIs

  • Check Context: Always remember if you’re in a client-side or server-side script. Using a server-side API (like GlideRecord) in a client script will result in errors, and vice-versa.
  • Use gs.info() / alert(): These are your best friends for debugging. Sprinkle them liberally to see what values your variables hold at different stages.
  • Scripts – Background: This module (sys.scripts.do) is invaluable for testing server-side Glide API snippets quickly without impacting users.
  • Browser Developer Tools: For client-side scripts, the browser’s developer console is indispensable. Look for errors in the console log.
  • Check Documentation: The ServiceNow Docs are incredibly detailed. If you’re unsure about a method’s parameters or return type, look it up!
  • Encoded Queries: For complex GlideRecord queries, build the filter on a list view, then right-click the filter breadcrumb and choose “Copy query” or “Copy query (encoded)”. This ensures correct syntax.

Conclusion: Empowering Your ServiceNow Journey

Phew! We’ve covered a lot, haven’t we? From the foundational GlideRecord for database interactions to the dynamic g_form for UI customization, and the indispensable gs for system utilities, understanding these Glide APIs unlocks a whole new level of control and flexibility in ServiceNow development.

Mastering these APIs takes practice, but the payoff is immense. You’ll be able to build more efficient automations, create intuitive user experiences, and troubleshoot complex issues with confidence. Keep experimenting in your non-production instances, consult the official documentation, and don’t shy away from diving into the existing code to see how others are leveraging these powerful tools.

Happy scripting, and may your ServiceNow instances always be customized to perfection!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top