Hey there, fellow ServiceNow enthusiast!
Ever found yourself staring at a blank script editor, needing to grab the raw data from a field, but feeling a bit unsure about the “right” way to do it? Or perhaps you’ve stumbled upon `getValue()` and `getDisplayValue()` and wondered, “What’s the difference, and when do I use which one?”
If any of that resonates, you’re in the perfect place. Today, we’re going to demystify one of ServiceNow’s most fundamental and frequently used scripting methods: `getValue()`. We’ll explore it from both the server-side and client-side perspectives, compare it with its display-oriented cousin, and arm you with the knowledge to wield it like a seasoned pro. So, grab your favorite beverage, settle in, and let’s dive into the fascinating world of field value retrieval!
The Essence of `getValue()`: Why We Need It
At its core, `getValue()` is your trusty tool for extracting the *actual, backend value* of a field. Think of it as peeking behind the curtain to see the raw data that ServiceNow stores in its database, rather than the user-friendly label or formatted text that might be shown on a form.
Why is this distinction so crucial? Imagine a ‘Priority’ field. To a user, it might display “1 – Critical” or “2 – High.” But internally, ServiceNow might store these as just ‘1’ or ‘2’. If you’re building logic that needs to evaluate or compare priorities, you typically want the raw ‘1’ or ‘2’ for consistency and accuracy. That’s where `getValue()` shines!
It’s not just about numbers, either. For reference fields, `getValue()` gives you the sys_id of the referenced record, which is invaluable for building relationships and queries. For choice fields, it provides the actual value stored, not the label. Understanding this fundamental concept is key to writing robust and reliable ServiceNow scripts.
`getValue()` on the Server-Side: Wielding GlideRecord
When you’re working behind the scenes in ServiceNow — think Business Rules, Script Includes, Scheduled Jobs, Fix Scripts, or UI Actions that run server-side — you’re often interacting with the database directly. This is where `GlideRecord` comes into play, acting as your primary interface for querying, inserting, updating, and deleting records.
Getting Started with GlideRecord and `getValue()`
The `GlideRecord` API is a powerhouse, and `getValue()` is one of its essential methods. When you query for a record and iterate through the results, `getValue()` allows you to pluck the specific field value you need from each record.
Let’s look at a practical example. Say you want to print the number and short description of all active incidents. You’d use `GlideRecord` to query the ‘incident’ table, and `getValue()` to extract those specific pieces of information.
var inc = new GlideRecord('incident');
inc.addQuery('active=true'); // Filter for active incidents
inc.query(); // Execute the query
while (inc.next()) {
// Use getValue() to get the actual number and short description
gs.print('Incident Number: ' + inc.getValue('number') + ' | Short Description: ' + inc.getValue('short_description'));
}
/*
Result (example):
Incident Number: INC0010001 | Short Description: Email not sending
Incident Number: INC0010002 | Short Description: Laptop performance issue
...
*/
Notice how straightforward it is? `inc.getValue(‘field_name’)` does exactly what it says on the tin. It’s concise, readable, and highly efficient for server-side operations.
Exercise 8: Working with IN operator and printing category of Software and Hardware (Expanded)
The reference material provides an excellent example combining `addQuery` with the `IN` operator and `getValue()`. Let’s break it down and understand its power.
var categoriesToFind = ['software', 'hardware']; // Define an array of categories
var incidentGR = new GlideRecord('incident');
incidentGR.addQuery('category', 'IN', categoriesToFind); // Query for incidents where category is 'software' OR 'hardware'
incidentGR.query();
gs.print('--- Incidents in Software or Hardware Category ---');
while(incidentGR.next()) {
// Print the incident number and short description for matching records
gs.print(incidentGR.getValue('number') + ' - ' + incidentGR.getValue('short_description') + ' (Category: ' + incidentGR.getValue('category') + ')');
}
/*
Result (example):
--- Incidents in Software or Hardware Category ---
INC0010005 - Microsoft Word crashes (Category: software)
INC0010008 - Monitor not working (Category: hardware)
INC0010012 - VPN connection issues (Category: software)
...
*/
Here, `getValue(‘category’)` retrieves the *actual stored value* for the category field. If your ‘Software’ category had a backend value of ‘software’ (which is common), then this works perfectly. This is a classic example of using `getValue()` to ensure your logic is based on the precise data, not just what’s displayed.
Exercise 18: Get value of particular field in the table (Refined)
The core concept of `getValue()` is demonstrated simply in this exercise:
var incidentGR = new GlideRecord('incident');
incidentGR.addQuery('active', 'true'); // A more robust way to add an active query
incidentGR.setLimit(5); // Let's limit the results for quicker testing
incidentGR.query();
gs.print('--- Short Descriptions of 5 Active Incidents ---');
while(incidentGR.next()){
gs.print( 'Short Description: ' + incidentGR.getValue('short_description'));
}
/*
Result (example):
--- Short Descriptions of 5 Active Incidents ---
Short Description: Cannot access shared drive
Short Description: Printer offline
Short Description: New user setup
Short Description: VPN connection drops frequently
Short Description: Software installation request
*/
This snippet perfectly illustrates the direct use of `getValue()` to pull out specific field data after a `GlideRecord` query. Simple, effective, and fundamental.
`getValue()` vs. `getDisplayValue()` (Server-Side)
This is where things get interesting! While `getValue()` retrieves the raw data, `getDisplayValue()` fetches the user-friendly, formatted representation of that data. Understanding when to use each is paramount.
Let’s revisit our ‘Priority’ field example. If `getValue(‘priority’)` gives you ‘1’, then `getDisplayValue(‘priority’)` would likely give you ‘1 – Critical’.
Exercise 19: Working `getDisplayValue()` method (Expanded)
The reference shows `inc.priority.getDisplayValue()`, which is a valid but slightly older syntax for Dot-walking on the current record. A more modern and generally recommended approach when working with a `GlideRecord` object is `incidentGR.getDisplayValue(‘field_name’)`.
var incidentGR = new GlideRecord('incident');
incidentGR.addQuery('priority', '1'); // Query for incidents with Priority 1
incidentGR.setLimit(3); // Limit for brevity
incidentGR.query();
gs.print('--- Priority 1 Incidents (Value vs. Display Value) ---');
while (incidentGR.next()){
var priorityValue = incidentGR.getValue('priority');
var priorityDisplayValue = incidentGR.getDisplayValue('priority'); // Recommended way
gs.print('Incident: ' + incidentGR.getValue('number') +
' | Priority Value: ' + priorityValue +
' | Priority Display Value: ' + priorityDisplayValue);
}
/*
Result (example):
--- Priority 1 Incidents (Value vs. Display Value) ---
Incident: INC0010020 | Priority Value: 1 | Priority Display Value: 1 - Critical
Incident: INC0010025 | Priority Value: 1 | Priority Display Value: 1 - Critical
Incident: INC0010030 | Priority Value: 1 | Priority Display Value: 1 - Critical
*/
See the difference? `getValue()` gives you ‘1’, perfect for logical comparisons or integrations that expect numeric codes. `getDisplayValue()` gives you ‘1 – Critical’, which is ideal for user notifications, reports, or logs where human readability is key.
When to use which (Server-Side):
- Use `getValue()` when:
- You need the raw, backend value for comparisons (`if (priorityValue == ‘1’)`).
- You’re passing values to integrations that expect specific codes (e.g., a third-party system expecting ‘sys_id’ for a reference).
- You’re dealing with choice fields where the backend value is more stable than the label (labels can change for localization, but values usually remain constant).
- Performing database operations or building queries.
- Use `getDisplayValue()` when:
- You’re presenting information to users (notifications, UI messages, custom reports).
- Logging information for debugging where readability is important.
- You need the user-friendly name of a reference field (e.g., “Abraham Lincoln” instead of “6816f79cc0a8016401c5a33be04be441”).
`getValue()` on the Client-Side: The Power of `g_form`
Now, let’s switch gears to the client-side. Client-side scripting in ServiceNow is all about making the user interface (UI) dynamic and responsive. This is where `g_form` takes center stage. The `g_form` API, available globally in Client Scripts and UI Policies with scripts, allows you to interact directly with the form the user is currently viewing in their browser.
Introducing `g_form` and Client Scripts
As the reference states:
- `g_form` is a client-side API, used to change the default behavior of the current record’s form.
- `g_form` methods run only on the client side (in the browser).
- You access `g_form` methods through the global `g_form` object.
- These methods are frequently used in Client Scripts and Catalog Client Scripts to make custom changes to the form view of records.
Just like `GlideRecord` has its `getValue()`, `g_form` also provides a `getValue()` method, but its context is entirely different. It retrieves the value of a field *as it currently appears on the form* in the user’s browser.
Exercise 1: Working with `g_form.getValue()` method
This method is used to get the specific field value from the current form. Let’s try it out!
How to run client-side code:
- Navigate to any Incident record (or any form you prefer).
- Open your browser’s JavaScript console. This is usually done by:
- Chrome/Edge/Firefox: Right-click anywhere on the page and select “Inspect” or “Inspect Element,” then go to the “Console” tab.
- Mac: Cmd+Option+J
- Windows: Ctrl+Shift+J
- Once in the console, you can type and execute JavaScript.
// Type this directly into your browser's JavaScript console while on an incident form:
alert(g_form.getValue('category'));
When you run this, a browser alert box will pop up, showing you the *actual stored value* of the ‘Category’ field for the incident record you are viewing. If the category displayed “Software,” the alert might show “software” (lowercase) if that’s the backend value.
When to use `g_form.getValue()`:
- Client-side Validations: Before a user submits a form, you might need to check the value of a field. E.g., “If ‘Assigned to’ is empty, prevent submission.”
- Dynamic Form Behavior: Show/hide fields, make fields mandatory, or set values based on another field’s value. E.g., “If ‘Category’ is ‘Hardware’, then make ‘Subcategory’ mandatory.”
- Calculations: Perform simple calculations on the form without hitting the server.
- Building Dynamic Queries (via GlideAjax): If you need to send a field’s value to the server for processing (e.g., retrieving related records), you’ll often grab it with `g_form.getValue()` and pass it via GlideAjax.
A Quick Look at `g_form.setValue()`
While our topic is `getValue()`, its counterpart `setValue()` is often used hand-in-hand. `g_form.setValue()` allows you to programmatically set the value of a field on the current form.
// Run these in sequence in your browser console on an incident form:
alert(g_form.getValue('category')); // See current category
g_form.setValue('category', 'hardware'); // Set category to 'hardware'
alert(g_form.getValue('category')); // See new category
You’ll notice the field on the form updates immediately! This client-side manipulation is incredibly powerful for creating interactive and intelligent forms.
`g_form.getValue()` vs. `g_form.getDisplayValue()` (Client-Side)
The distinction here mirrors the server-side: `getValue()` for raw, `getDisplayValue()` for formatted. The syntax is identical to the server-side `GlideRecord` methods, just prefixed with `g_form`.
// Example to run in browser console on an incident form with 'Priority' field
var priorityVal = g_form.getValue('priority');
var priorityDisplayVal = g_form.getDisplayValue('priority');
console.log('Priority Field Value (Raw): ' + priorityVal);
console.log('Priority Field Display Value (Formatted): ' + priorityDisplayVal);
// You might see something like:
// Priority Field Value (Raw): 1
// Priority Field Display Value (Formatted): 1 - Critical
The choice between them follows the same logic as server-side: use `getValue()` for internal logic, comparisons, or passing to server scripts (e.g., GlideAjax). Use `getDisplayValue()` for messages, alerts, or updating other display-only elements on the form where human readability is paramount.
`getValue()` vs. `getDisplayValue()`: The Ultimate Showdown
Let’s consolidate our understanding of these two crucial methods across both client and server contexts.
Key Differences and When to Use Them:
| Feature | `getValue()` | `getDisplayValue()` |
|---|---|---|
| What it returns | The raw, backend value stored in the database. For reference fields, this is the `sys_id`. For choice lists, it’s the backend value (e.g., ‘1’, ‘software’). | The user-friendly, formatted value displayed on the form. For reference fields, this is the display name (e.g., “System Administrator”). For choice lists, it’s the label (e.g., “1 – Critical”, “Software”). |
| Primary Use Case | Logical comparisons, database queries, integrations expecting specific IDs/codes, internal data processing. | Presenting data to users (alerts, messages, reports), logging, making data human-readable. |
| Contexts Available | Server-side (`GlideRecord`) and Client-side (`g_form`). | Server-side (`GlideRecord`) and Client-side (`g_form`). |
| Example: Priority field (‘1 – Critical’) | Returns: `’1’` | Returns: `’1 – Critical’` |
| Example: Caller field (reference to user) | Returns: `’a8fbc286c0a8016401c5a33be04be441’` (sys_id) | Returns: `’Abraham Lincoln’` (display name) |
| Performance Consideration | Generally faster as it’s a direct lookup of the stored value. | Can be slightly slower for reference fields as it might involve an additional lookup to retrieve the display name. (Minor for most use cases, but good to know for high-volume operations). |
Remember this table, internalize it, and you’ll always pick the right method for the job!
Advanced Scenarios and Best Practices
Now that we’ve covered the basics, let’s explore some nuanced aspects and best practices for using `getValue()` effectively.
Handling Different Field Types
- Reference Fields: `getValue()` returns the `sys_id`. This is crucial for linking records or performing queries on the referenced table. `getDisplayValue()` returns the display name.
- Choice Fields: `getValue()` returns the internal value. `getDisplayValue()` returns the label. Always prefer `getValue()` for comparisons as labels can change due to localization.
- Boolean Fields: `getValue()` typically returns ‘true’ or ‘false’ (as strings) or sometimes ‘1’ or ‘0’. It’s often safer to compare against ‘true’/’false’ strings or convert to boolean if strict type checking is needed.
var activeValue = incidentGR.getValue('active'); if (activeValue == 'true') { // or if (activeValue === '1') // ... }On the client-side, `g_form.getBooleanValue(‘field_name’)` is often preferred for boolean fields as it explicitly returns a JavaScript boolean `true` or `false`.
- Date/Time Fields: `getValue()` returns the internal UTC date/time string (e.g., “YYYY-MM-DD HH:MM:SS”). `getDisplayValue()` returns the date/time formatted according to the user’s locale and time zone.
Null Checks and Undefined Values
It’s always a good practice to check if a value exists before trying to use it, especially if the field might be empty or optional. An empty field will return `null` or an empty string (`”`).
var description = incidentGR.getValue('description');
if (description) { // Checks if description is not null, undefined, or empty string
gs.print('Description exists: ' + description);
} else {
gs.print('Description is empty or null.');
}
Performance Considerations
While generally efficient, remember that `getDisplayValue()` (especially for reference fields) might involve an extra lookup compared to `getValue()`. For single instances, this is negligible. However, if you’re processing thousands of records in a loop on the server, and only need the raw `sys_id`, sticking with `getValue()` can offer a marginal performance benefit.
Security Implications (ACLs)
When you use `getValue()` or `getDisplayValue()` on the server-side within a `GlideRecord` object, the values retrieved are subject to the Access Control Lists (ACLs) that apply to the record and field. If the user context running the script (or the system itself) does not have read access to a field, `getValue()` might return `null` or an empty string, or even throw an error depending on the exact context and platform version. Always be mindful of ACLs when debugging unexpected `null` values.
Troubleshooting Common `getValue()` Issues
Even seasoned developers hit snags. Here are some common issues and how to troubleshoot them:
1. Getting `null` or `undefined` when expecting a value
- Check Field Name: Is the field name spelled correctly? Case-sensitive? (e.g., `short_description` vs. `Short_Description`).
- Field Actually Populated?: Is the field truly populated on the record you’re querying/viewing? Open the record in the UI to confirm.
- Server-side (GlideRecord):
- Did your `GlideRecord` query return any results? Use `gs.info(incidentGR.getRowCount())` to check.
- Did you call `incidentGR.next()` within your `while` loop? Without it, you’re not moving to the first or subsequent records.
- Client-side (g_form):
- Is the script running on the correct form view?
- Is the field even present on the current form?
- Is it a variable in a Catalog Item? For variables, you often need `g_form.getValue(‘variables.your_variable_name’)`.
- ACLs: Does the current user context (or system context for server scripts) have read access to the field?
2. Getting the wrong value (e.g., sys_id when expecting a name)
- This is the classic `getValue()` vs. `getDisplayValue()` mix-up. If you’re seeing a sys_id and want the name, switch to `getDisplayValue()`. If you’re seeing a label and want the backend code, use `getValue()`.
3. Client-side `getValue()` not reflecting recent changes
- If a user has just typed something into a field, `g_form.getValue()` will grab that *current* value, even if the record hasn’t been saved. This is usually the desired behavior on the client-side.
- If a value was *set* by another client script or UI Policy, `getValue()` will reflect that immediately.
4. “g_form is not defined” error
- This means you’re trying to use `g_form` in a server-side script (e.g., a Business Rule or Script Include). `g_form` is *only* available on the client-side. For server-side, you’ll be using `current.field_name` (if it’s the current record) or `GlideRecord` objects.
Interview Relevance: Mastering `getValue()` for Your Next Role
You can bet your bottom dollar that `getValue()` and its distinctions will come up in ServiceNow developer interviews. Interviewers love to gauge your foundational understanding and practical application skills.
Here’s how this topic might be probed:
- “Explain the difference between `getValue()` and `getDisplayValue()` in ServiceNow.” (A core question, be ready to explain contexts and examples.)
- “When would you use `g_form.getValue()` versus `current.getValue()` or `gr.getValue()`?” (Tests your understanding of client-side vs. server-side context.)
- “You have a reference field for ‘Assigned To’. How would you get the user’s name? How would you get their sys_id?” (Directly tests `getValue()` vs. `getDisplayValue()` for reference fields.)
- “Describe a scenario where using `getDisplayValue()` for a comparison might lead to issues.” (Prompts you to explain the pitfalls of using labels for logic.)
- “How would you retrieve the value of a variable on a Service Catalog form using a Client Script?” (Tests `g_form.getValue(‘variables.variable_name’)` knowledge.)
Practicing with these methods and understanding their nuances will not only make you a better ServiceNow developer but also boost your confidence in technical interviews.
Wrapping It Up
Phew! We’ve covered a lot of ground today, haven’t we? From its humble beginnings as a way to peek at raw data to its critical role in both server-side `GlideRecord` operations and client-side `g_form` manipulations, `getValue()` is truly a cornerstone of ServiceNow development.
Remember these key takeaways:
- `getValue()` retrieves the raw, backend value.
- `getDisplayValue()` retrieves the user-friendly, formatted value.
- Both exist for server-side (`GlideRecord`) and client-side (`g_form`) contexts.
- Choose the right method based on whether you need data for logic/integrations (`getValue()`) or presentation/readability (`getDisplayValue()`).
- Always perform null checks and be mindful of field names and ACLs.
The best way to solidify this knowledge is to get your hands dirty. Fire up your personal developer instance, open the script console, write some Client Scripts and Business Rules, and experiment! The more you practice, the more intuitive these powerful methods will become.
Happy scripting, and may your field values always be retrieved precisely as you intend!