Mastering ServiceNow: Top 10 GlideRecord Scenarios Every Developer Should Know
Hey there, fellow ServiceNow enthusiasts! If you’ve been navigating the intricate world of ServiceNow development, chances are you’ve had your fair share of encounters with GlideRecord. This powerful API is the backbone of server-side scripting, allowing us to interact with virtually any data in the platform. From creating records on the fly to orchestrating complex business logic, GlideRecord is your go-to tool.
I’ve been diving deep into ServiceNow for a while now, starting my journey back in the Rome release and progressing through San Diego, Tokyo, Utah, Vancouver, and now I’m comfortably working with the latest, Washington D.C.. Over these releases, I’ve seen and implemented a multitude of GlideRecord scenarios. Today, I want to share some of the most impactful and frequently encountered ones that I believe every ServiceNow developer should have in their toolkit. These aren’t just snippets of code; they represent practical solutions to common challenges, making your scripts more robust, efficient, and maintainable.
Let’s jump right in and explore some of these essential GlideRecord use cases!
The GlideRecord Essentials: A Quick Refresher
Before we dive into the scenarios, a quick recap for those who might be newer to the platform or just need a refresher. GlideRecord is your primary interface for server-side database operations in ServiceNow. You use it to query, create, update, and delete records in any table.
The basic structure typically looks like this:
var gr = new GlideRecord('your_table_name'); // Initialize GlideRecord for a specific table
gr.addQuery('field_name', 'value'); // Add a condition to filter records
gr.query(); // Execute the query
while (gr.next()) { // Loop through the returned records
// Perform operations on each record
// gr.setValue('field_name', 'new_value');
// gr.update();
}
Understanding this foundational pattern is key to mastering the scenarios we’ll cover.
Top 10 ServiceNow GlideRecord Scenarios
Now, let’s get to the good stuff. Here are 10 scenarios where GlideRecord shines, along with practical explanations and code examples.
1. User and Group Management: The Foundation of Permissions
Managing users and groups is a fundamental aspect of ServiceNow administration and development. GlideRecord plays a crucial role in automating these tasks, especially when dealing with large numbers of users or complex permission structures.
Creating Users with Script
Sometimes, you need to create user accounts programmatically. This could be for integrations, bulk data loading, or custom user onboarding processes.
Scenario: Programmatically Creating a New User Account
Use Case: Imagine an integration that provisions new hires into ServiceNow, automatically creating their user records. The sys_user table stores user information.
var userGr = new GlideRecord('sys_user');
userGr.initialize(); // Prepare a new record
userGr.username = 'jdoe'; // Set the username
userGr.firstname = 'John'; // Set the first name
userGr.lastName = 'Doe'; // Set the last name
userGr.email = 'jdoe@example.com'; // Set the email address
// You can set many other fields here like department, manager, etc.
userGr.insert(); // Save the new user record to the database
Interview Relevance: This is a classic interview question. Be prepared to explain the `initialize()` and `insert()` methods.
Creating Groups with Script
Similarly, you might need to create new groups for teams, departments, or specific projects.
Scenario: Creating a New Assignment Group
Use Case: Automatically creating an assignment group when a new department is onboarded in another system.
var newGr = new GlideRecord('sys_user_group');
newGr.initialize();
newGr.name = 'Testing Group'; // Name of the new group
// Manager field is a reference to sys_user, so we use the sys_id
userGr.manager = '62826bf03710200044e0bfc8bcbe5df1'; // sys_id of the manager
newGr.email = 'testing@example.com'; // Email for the group
newGr.description = 'This is a test group for demonstration purposes.';
newGr.insert();
Adding Permissions (Roles) to Users and Groups
A crucial aspect of security is assigning roles to users and groups. A best practice in ServiceNow is to manage permissions primarily through groups. When an employee leaves, removing them from a group automatically revokes their permissions.
Scenario: Assigning the ‘itil’ Role to a User
Use Case: Granting ITIL access to a newly created user account.
var userRole = new GlideRecord('sys_user_has_role');
userRole.initialize();
userRole.user = '62826bf03710200044e0bfc8bcbe5df1'; // sys_id of the user
userRole.role = '2831a114c611228501d4ea6c309d626d'; // sys_id of the 'itil' role
userRole.insert();
Scenario: Assigning a Role to a Group
Use Case: Giving an entire team the ‘catalog_admin’ role.
var grpRole = new GlideRecord('sys_group_has_role');
grpRole.initialize();
grpRole.group = '477a05d153013010b846ddeeff7b1225'; // sys_id of the group
grpRole.role = '2831a114c611228501d4ea6c309d626d'; // sys_id of the 'itil' role (example)
grpRole.insert();
Adding and Removing Group Members
Managing group memberships is essential for role-based access control.
Scenario: Adding a User to an Existing Group
Use Case: Automatically adding a user to a specific department’s support group when their role changes.
var grMem = new GlideRecord('sys_user_grmember');
grMem.initialize();
grMem.user = '62826bf03710200044e0bfc8bcbe5df1'; // sys_id of the user
grMem.group = '477a05d153013010b846ddeeff7b1225'; // sys_id of the group
grMem.insert();
Scenario: Removing a User from a Group
Use Case: Automatically removing a user from a project-specific group when their project involvement ends.
var grMem = new GlideRecord('sys_user_grmember');
// Query for the specific membership record
grMem.addQuery('user', '62826bf03710200044e0bfc8bcbe5df1'); // sys_id of the user
grMem.addQuery('group', '477a05d153013010b846ddeeff7b1225'); // sys_id of the group
grMem.query();
if (grMem.next()) {
grMem.deleteRecord(); // Remove the membership record
}
Troubleshooting: If a user is already removed or never existed in the group, the grMem.next() will be false, and `deleteRecord()` won’t be called, preventing errors.
2. Creating Core Service Management Records
GlideRecord is indispensable for automating the creation of tickets like Incidents, Problems, and Change Requests. This is often part of automated workflows, integrations, or proactive problem management.
Creating Incident Records
Automatically creating incidents based on alerts, customer requests, or system events.
Scenario: Automated Incident Creation from a Monitoring Alert
Use Case: A system monitoring tool detects a critical server issue and sends an alert that triggers a ServiceNow business rule to create an incident.
var gr = new GlideRecord('incident');
gr.initialize();
gr.caller_id = '86826bf03710200044e0bfc8bc5d94'; // sys_id of the caller
gr.category = 'hardware'; // e.g., 'hardware', 'software'
gr.subcategory = 'server'; // e.g., 'server', 'laptop'
// cmdb_ci is a reference to the Configuration Item
gr.cmdb_ci = 'affd3c8437201000deeabfc8bcbe5dc3'; // sys_id of the affected CI
gr.short_description = 'Critical server issue detected: High CPU utilization.';
gr.description = 'The monitoring system reported sustained high CPU usage on server XYZ.';
// assignment_group is a reference to sys_user_group
gr.assignment_group = 'a715cd759f2002002920bde8132e7018'; // sys_id of the assignment group
gr.insert();
SEO Optimization: Using terms like “Automated Incident Creation,” “ServiceNow Business Rule,” and “GlideRecord Incident” helps in searchability.
Creating Problem Records
When recurring incidents point to a potential underlying issue, a Problem record is created to investigate and find a permanent fix.
Scenario: Creating a Problem Record from Multiple Incidents
Use Case: A business rule detects that more than 10 similar incidents have occurred within an hour and automatically creates a Problem record to initiate root cause analysis.
var gr = new GlideRecord('problem');
gr.initialize();
gr.caller_id = '86826bf03710200044e0bfc8bc5d94'; // sys_id of the reporter
gr.category = 'software';
gr.subcategory = 'database';
gr.cmdb_ci = 'affd3c8437201000deeabfc8bcbe5dc3'; // sys_id of the affected CI
gr.short_description = 'Frequent database connection errors reported.';
gr.description = 'Multiple users are reporting intermittent errors when connecting to the main database.';
gr.assignment_group = 'a715cd759f2002002920bde8132e7018'; // sys_id of the assignment group
gr.insert();
Creating Change Requests
For planned modifications to the IT infrastructure, Change Requests are essential. GlideRecord can automate their creation as part of deployment pipelines or scheduled maintenance.
Scenario: Automating Change Request for Scheduled Software Update
Use Case: A scheduled job creates a Change Request for a planned operating system patch deployment on a set of servers.
var gr = new GlideRecord('change_request');
gr.initialize();
gr.category = 'software'; // e.g., 'software', 'hardware', 'network'
gr.subcategory = 'patch'; // e.g., 'patch', 'upgrade', 'configuration'
gr.cmdb_ci = 'affd3c8437201000deeabfc8bcbe5dc3'; // sys_id of the affected CI
gr.short_description = 'Scheduled OS Patch Deployment - Q3 2024';
gr.description = 'Deploying the latest security patches for Windows Server 2019 across all production servers.';
gr.assignment_group = 'a715cd759f2002002920bde8132e7018'; // sys_id of the assignment group
// Set planned start and end dates for the change
gr.work_start = '2024-08-15 22:00:00';
gr.work_end = '2024-08-15 23:59:00';
gr.insert();
3. Automating Record State Transitions
GlideRecord is vital for ensuring that related records are updated appropriately when a primary record’s state changes. This maintains data integrity and workflow consistency.
Closing Child Incidents When Parent is Closed
A common requirement is to automatically close any associated child incidents when the parent incident is resolved.
Scenario: Automatically Closing Child Incidents
Use Case: If a major outage incident is resolved and closed, all related sub-incidents should also be closed automatically to reflect the resolution.
This logic is best implemented as an After Business Rule on the incident table.
// Business Rule: Auto-Close Child Incidents
// Table: Incident
// When: After
// Update: True
// Condition: current.state.changesTo(7); // Assuming state 7 is 'Closed'
if (current.state == 7 && current.parent == '') { // Check if the current incident is closed and it's not a child itself
var grChild = new GlideRecord('incident');
grChild.addQuery('parent', current.sys_id); // Find incidents where parent field points to this incident
grChild.query();
while (grChild.next()) {
grChild.state = 7; // Set the state to Closed for the child
grChild.update(); // Update the child incident record
}
}
Troubleshooting: Ensure the state value `7` correctly maps to your ‘Closed’ state. Also, verify the `parent` field is empty for top-level incidents. You might add a check for `current.state != previous.state` to ensure it only triggers on state *changes* to closed.
Preventing Closure if Tasks are Open
Business rules can enforce data integrity by preventing record closure if associated tasks are still open.
Scenario: Preventing Incident Closure with Open Incident Tasks
Use Case: An ITIL user tries to close an incident, but there are still open incident tasks associated with it. The system should block the closure and inform the user.
This logic is best implemented as a Before Business Rule on the incident table.
// Business Rule: Prevent Incident Close with Open Tasks
// Table: Incident
// When: Before
// Insert: False
// Update: True
// Condition: current.state.changesTo(3); // Assuming state 3 is 'Closed'
var grTask = new GlideRecord('incident_task');
grTask.addQuery('incident', current.sys_id); // Find tasks linked to this incident
grTask.addQuery('state', '!=', 3); // Assuming state 3 is 'Closed' for incident tasks. Adjust if your 'Closed' state is different.
grTask.query();
if (grTask.hasNext()) { // If there are any open tasks found
gs.addErrorMessage('Cannot close the incident because there are open tasks. Please close all associated incident tasks first.');
current.setAbortAction(true); // Prevent the update (closure)
}
Interview Relevance: This demonstrates understanding of Before Business Rules, `setAbortAction()`, and `addErrorMessage()` for user feedback.
Closing Incidents When Associated Problem is Closed
When a Problem is resolved, all its associated Incidents should also be closed, assuming the Problem’s resolution addresses the root cause of the Incidents.
Scenario: Automatically Closing Incidents Linked to a Resolved Problem
Use Case: After the root cause of a recurring issue is identified and fixed in a Problem record, all active incidents related to that problem are automatically closed.
This logic is best implemented as an After Business Rule on the problem table.
// Business Rule: Auto-Close Incidents on Problem Closure
// Table: Problem
// When: After
// Update: True
// Condition: current.state.changesTo(7); // Assuming state 7 is 'Closed' for Problems
if (current.state == 7) { // If the problem is now closed
var grIncident = new GlideRecord('incident');
// Query for incidents that have a problem_id referencing this problem
grIncident.addQuery('problem_id', current.sys_id);
grIncident.addQuery('state', '!=', 7); // Only update incidents that are NOT already closed
grIncident.query();
while (grIncident.next()) {
grIncident.state = 7; // Set the incident state to Closed
grIncident.update(); // Update the incident
}
}
Troubleshooting: Make sure the `problem_id` field is correctly populated on the incident. The state values for Problem and Incident must be correctly identified.
4. Working with Current User Information
GlideRecord, combined with the gs object and g_user object, allows you to leverage information about the currently logged-in user for context-aware operations.
Getting Current User’s sys_id
You’ll frequently need the current user’s `sys_id` for creating records, setting fields, or performing checks.
Scenario: Setting the Caller of a New Incident to the Current User
Use Case: When a user logs an incident through the portal, their user record should automatically be populated in the ‘Caller’ field.
Client-side:
// In a Client Script or UI Policy script
var currentUserId = g_user.userID; // Gets the sys_id of the logged-in user
g_form.setValue('caller_id', currentUserId); // Assuming 'caller_id' is the field name on the form
Server-side:
// In a Business Rule or Script Include
var currentUserId = gs.getUserID(); // Gets the sys_id of the logged-in user
current.setValue('caller_id', currentUserId); // Using 'current' object in a business rule
Interview Relevance: Differentiating between client-side (`g_user.userID`) and server-side (`gs.getUserID()`) is crucial.
Checking if User is a Member of a Group
This is fundamental for controlling access, routing, or triggering specific logic based on group membership.
Scenario: Displaying a Specific UI Action Only for ITIL Users
Use Case: A “Re-assign to Tier 2” UI Action should only be visible to users who are members of the “IT Support – Tier 2” group.
This is often done via UI Action conditions.
// In the condition field of a UI Action
gs.getUser().isMemberOf('IT Support - Tier 2'); // Returns true if the current user is in this group
Note: You can also use the group’s `sys_id` instead of the name for better performance and stability.
5. Creating Records from Various Sources
ServiceNow offers multiple ways to get data into tables, and GlideRecord is the programming interface behind many of them.
Ways to Create Records
Understanding these methods is key to choosing the right tool for the job.
Scenario: Overview of Record Creation Methods
Use Case: A comprehensive understanding of how data enters the ServiceNow platform.
- Form Submission: The most basic way, users fill out a form and submit it.
- Record Producer: A specialized form that creates one or more records, often used in the Service Portal.
- Email: Inbound email actions can create records based on incoming emails.
GlideRecord: Server-side scripting for programmatic creation (as seen in previous examples).- Excel Sheet Import: Using the “Import Set” functionality or “Load Data” for bulk imports.
- External Systems: Integrations via REST APIs, SOAP, or scheduled data imports.
Interview Relevance: This question tests your breadth of knowledge about ServiceNow’s data ingestion capabilities.
6. Field Manipulation: Mandatory, Read-Only, and More
Controlling field behavior is critical for user experience and data integrity. While UI Policies and Data Policies are often the primary tools, GlideRecord plays a role in setting these attributes dynamically.
Ways to Make Fields Mandatory or Read-Only
There are several layers of control for field attributes.
Scenario: Controlling Field Properties
Use Case: Ensuring critical fields are filled and sensitive fields cannot be altered by unauthorized users.
- Dictionary Properties: Setting `mandatory` or `readonly` attributes directly on the field’s dictionary entry. This is static.
- Dictionary Overrides: Overriding dictionary attributes for specific tables (e.g., making a field mandatory on `incident` but not on its child table).
- UI Policies: Client-side scripting to dynamically set mandatory, read-only, visible, or hidden attributes based on form conditions.
- Data Policies: Server-side and client-side enforcement of mandatory and read-only attributes. They are often more robust for critical data.
g_form.setMandatory()(Client-side): A scripting method to dynamically set a field’s mandatory status on the client.current.setReadOnly()/current.setMandatory()(Server-side): While not directly setting the *attribute* of a field for future interactions, these methods within a Before Business Rule can prevent a record update if conditions aren’t met or to conditionally make fields read-only for the current transaction. (This is less common for the typical “mandatory/read-only” requirement and more for transaction control.)
Troubleshooting: The order of execution matters. Dictionary settings are the base, then Data Policies, then UI Policies. UI Policies can be overridden by Client Scripts.
Understanding Reference Qualifiers
Reference qualifiers are crucial for filtering the records displayed in reference fields, ensuring users select appropriate related data.
Scenario: Filtering Reference Field Choices
Use Case: On an Incident form, when selecting a ‘Configuration Item’ (CI), you only want to show CIs that are of the ‘Server’ class.
Types of Reference Qualifiers:
-
Simple: Uses a direct query string.
active=true^class=cmdb_ci_server -
Dynamic: Uses a pre-defined “Dynamic Filter Option” that can be reused and parameterized.
Example: Displaying only CIs that are in the same datacenter as the caller’s location.
Configuration: Define a Dynamic Filter Option in “System Definition > Dynamic Filter Options”.
-
Advanced: Uses custom JavaScript code to construct the query. This offers the most flexibility.
javascript: 'active=true^class.name=server^assignment_group=' + current.assignment_group;This example filters CIs that are active, named ‘server’, and assigned to the same group as the incident.
Differences:
- Simple vs. Dynamic: Simple is static; Dynamic can adapt to context defined in the Dynamic Filter Option.
- Dynamic vs. Advanced: Dynamic uses predefined options; Advanced uses custom JavaScript for maximum control.
- Simple vs. Advanced: Simple is a fixed query; Advanced allows complex logic and calculations.
Interview Relevance: This is a very common topic. Be ready to explain each type and provide examples.
Dependent Values
Dependent values create cascaded dropdowns, where the choices in one field are filtered based on the selection in another.
Scenario: Cascading Category and Subcategory
Use Case: When a user selects ‘Hardware’ for the Incident ‘Category’, the ‘Subcategory’ dropdown should only show options like ‘Laptop’, ‘Desktop’, ‘Printer’, etc. If they select ‘Software’, it should show ‘Operating System’, ‘Application’, etc.
Configuration:
- Go to the dictionary entry for the dependent field (e.g.,
subcategory). - In the “Attributes” field, add
dependent_field=category(replacecategorywith the actual parent field name). - In the “Choices” related list for the
subcategorytable, define choices and link them to specific parent field values.
Troubleshooting: Ensure the `dependent_field` attribute is correctly set and that choices are defined for each parent value. Ensure the parent field itself has defined choices.
Calculated Values
Fields can be automatically populated with values derived from other fields using calculations.
Scenario: Calculating a Due Date Based on Priority
Use Case: Automatically setting a ‘Due Date’ for an Incident based on its ‘Priority’. For example, P1 incidents are due in 4 hours, P2 in 24 hours, etc.
Configuration:
- Go to the dictionary entry for the calculated field (e.g.,
due_date). - Set the Type to ‘Calculated’.
- In the “Calculated value” script field, use the
currentobject.
// Script in the Calculated value field for 'due_date'
var dueDate = new GlideDateTime();
var priority = current.priority.toString(); // Get the priority value
if (priority == '1') { // P1 - Critical
dueDate.add(new GlideDuration(4 * 60 * 60 * 1000)); // Add 4 hours
} else if (priority == '2') { // P2 - High
dueDate.add(new GlideDuration(24 * 60 * 60 * 1000)); // Add 24 hours
} else { // Default for P3, P4
dueDate.add(new GlideDuration(7 * 24 * 60 * 60 * 1000)); // Add 7 days
}
answer = dueDate;
Troubleshooting: Ensure the priority values in the script match your actual priority values. Test with different priority levels.
7. Understanding the `current` Object
The `current` object is fundamental to server-side scripting, representing the record being processed.
What is the `current` Object?
It’s an instance of GlideRecord that holds the data of the record currently being acted upon by a server-side script (like a Business Rule, Script Action, or Workflow script).
How to Set Field Values on the `current` Object
You use methods like `setValue()` and `setDisplayValue()` to update the record’s fields.
Scenario: Updating the ‘Assigned To’ Field
Use Case: In a Business Rule, automatically assign an incident to a specific user based on certain criteria.
// Assuming this is in a Business Rule script
var assigneeSysId = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6'; // sys_id of the user
current.setValue('assigned_to', assigneeSysId); // Set the sys_id for a reference field
current.setDisplayValue('assigned_to', 'John Doe'); // Set the display value (useful for logging, but `setValue` is for actual data persistence)
Key Difference: `setValue()` sets the underlying value (usually `sys_id` for reference fields). `setDisplayValue()` sets the human-readable label, which is less common for actual record updates but useful for logging or informational purposes.
Troubleshooting: Always use `setValue()` with the `sys_id` for reference fields. Using `setDisplayValue()` to set the actual data can lead to incorrect data if the display value doesn’t match an existing record.
8. UI Policies vs. Data Policies: When to Use Which
Understanding the difference and application of UI Policies and Data Policies is crucial for effective client-side and server-side data control.
What are UI Policies?
UI Policies are client-side scripts that dynamically control the behavior of form fields. They can make fields mandatory, read-only, visible, hidden, or set their default values based on conditions.
UI Policy Features
- Global Checkbox: If checked, the UI Policy applies to all views. If unchecked, you specify which views it affects.
- Reverse if False: When checked, the actions of the UI Policy are reversed if the condition evaluates to false. For example, if a field is made mandatory when true, it becomes optional when false.
- On Load Checkbox: If checked, the UI Policy runs when the form loads. If unchecked, it only runs when a field value changes that meets the condition.
- Inherit Checkbox: If checked, the UI Policy also applies to tables that extend the current table (child tables).
- Run Scripts Checkbox: Allows you to execute client-side scripts within the UI Policy actions for more complex logic.
What are Data Policies?
Data Policies enforce data consistency and integrity across all data sources, including forms, integrations, and imports. They can set mandatory and read-only attributes on fields.
When UI Policies Cannot Be Converted to Data Policies
Data Policies are primarily for mandatory and read-only attributes. UI Policies have broader capabilities:
- Controlling Data Visibility (Visible/Hidden): Data Policies cannot control if a field is visible or hidden.
- Controlling Views: UI Policies can be view-specific; Data Policies are not.
- Controlling Related Lists: UI Policies can show/hide related lists; Data Policies cannot.
- Controlling Scripts: UI Policies can execute client-side scripts for complex logic, which Data Policies don’t directly support in the same way.
Conversion: You can convert a UI Policy to a Data Policy by clicking “Convert this as Data Policy” on the UI Policy form, but only for its inherent data control capabilities (mandatory/read-only).
9. Advanced Scripting with `GlideRecord`
Beyond basic CRUD operations, GlideRecord supports advanced querying and manipulation techniques.
`current.setAbortAction()`
This method is essential within Before Business Rules to stop the current database operation (insert, update, delete) if certain conditions are not met.
Scenario: Stopping an Update if Validation Fails
Use Case: Preventing a Change Request from being marked as ‘Complete’ if the ‘Work notes’ field is empty.
This would be a Before Business Rule on the change_request table.
// Business Rule: Prevent Completion without Work Notes
// Table: Change Request
// When: Before
// Update: True
// Condition: current.state.changesTo(8); // Assuming state 8 is 'Complete'
if (current.state == 8 && current.work_notes.getJournalEntry(1) == '') { // Check if state is changing to Complete AND work notes are empty
gs.addErrorMessage('Work notes are mandatory for completing a Change Request.');
current.setAbortAction(true); // Stop the update
}
`gr.getDisplayValue()`
Retrieving the human-readable value of a reference field or choice list.
Scenario: Logging the Name of an Assigned User
Use Case: In a Business Rule that closes an incident, log who the incident was assigned to.
// Assuming you have already queried an incident record into 'grIncident'
var assignedUserName = grIncident.assigned_to.getDisplayValue(); // Get the display name of the assigned user
gs.info('Incident ' + grIncident.number + ' was assigned to: ' + assignedUserName);
Note: You can access related fields directly using dot-walking (e.g., `grIncident.assigned_to.department.name`).
10. `GlideRecord` vs. `gs.getRefRecord()` and `gs.getUser()`
Understanding when to use different methods for retrieving related information is key to writing efficient code.
`gs.getUser()` and `gs.getUserID()`
These are straightforward methods for getting the current user’s object and sys_id, respectively. They are generally preferred over querying `sys_user` for the current user.
`gs.getRefRecord()`
This method retrieves a GlideRecord object for a referenced record. It’s a more efficient way to get related record data than performing a separate GlideRecord query if you only need one specific referenced record.
Scenario: Getting the Assignment Group’s Name from an Incident
Use Case: In a business rule, you need the name of the assignment group for an incident.
Using GlideRecord (less efficient if only one record needed):
var incidentGr = new GlideRecord('incident');
if (incidentGr.get('sys_id', current.sys_id)) { // Assuming 'current' is the incident being processed
var assignmentGroupId = incidentGr.assignment_group.toString();
var groupGr = new GlideRecord('sys_user_group');
if (groupGr.get(assignmentGroupId)) {
var groupName = groupGr.name;
gs.info('Assignment group name: ' + groupName);
}
}
Using `getDisplayValue()` (dot-walking):
var incidentGr = new GlideRecord('incident');
if (incidentGr.get('sys_id', current.sys_id)) {
var groupName = incidentGr.assignment_group.getDisplayValue(); // Direct dot-walking
gs.info('Assignment group name: ' + groupName);
}
Using `gs.getRefRecord()`:
var incidentGr = new GlideRecord('incident');
if (incidentGr.get('sys_id', current.sys_id)) {
var assignmentGroupRecord = gs.getRefRecord(incidentGr.assignment_group); // Get GlideRecord for the referenced group
if (assignmentGroupRecord) {
var groupName = assignmentGroupRecord.name;
gs.info('Assignment group name: ' + groupName);
}
}
Efficiency: Dot-walking with `getDisplayValue()` is often the most concise and efficient for simply getting display values. `gs.getRefRecord()` is useful when you need the full GlideRecord object of the referenced record for further operations.
Interview Relevance: This tests your understanding of choosing the right tool for fetching related data efficiently.
Conclusion
GlideRecord is an incredibly versatile tool in the ServiceNow developer’s arsenal. Mastering these common scenarios will not only make you more efficient but also more confident in tackling complex development tasks.
From user and group management to automating ticket creation and enforcing data integrity, these examples cover a broad spectrum of real-world applications. Remember to always consider performance, security, and maintainability when writing your scripts. The ServiceNow platform, and the Washington D.C. release especially, offers robust capabilities, and understanding how to leverage GlideRecord effectively is key to unlocking its full potential.
Keep practicing, keep exploring, and happy scripting!