Unlocking Data: A Deep Dive into ServiceNow’s `getValue()` Method
Hey there, fellow ServiceNow enthusiast! Ever felt like you’re constantly digging through the platform, trying to extract just the right piece of information from a record, a form, or even a date object? If so, you’re not alone. One of the most fundamental and versatile methods you’ll encounter in your ServiceNow journey is getValue(). It’s like your trusty Swiss Army knife for data retrieval, present across various APIs and contexts, each with its own subtle nuance.
In this article, we’re going to pull back the curtain on getValue(). We’ll explore where it lives, what it does, and more importantly, when and why you should use it. We’ll dive into practical examples, discuss common pitfalls, and even touch upon its relevance in those dreaded technical interviews. So, grab a coffee, and let’s unravel the magic of getValue() together!
Understanding getValue() is not just about knowing a method; it’s about understanding how ServiceNow stores and presents data. Master this, and you’ll write cleaner, more efficient, and more robust scripts across the platform.
Server-Side Retrieval: `getValue()` with GlideRecord
Let’s kick things off with arguably the most common use case for getValue(): server-side scripting, specifically when you’re working with records pulled from the database using GlideRecord.
What it Does: Getting Field Values from the Database
When you use getValue() on a GlideRecord object, you’re asking for the actual, raw, stored value of a specific field directly from the database. Think of it as peeking into the data’s true form, unformatted and unadorned. This is incredibly powerful when you need to perform comparisons, calculations, or simply retrieve the precise data that ServiceNow uses internally.
Basic Usage: A First Glance
Imagine you’re building a report or a script that needs to process all active incidents. You’d query the incident table and then, for each incident, you might want to grab its short_description. Here’s how you’d do it:
var inc = new GlideRecord('incident');
inc.addQuery('active', true); // More explicit than 'active=true' for clarity
inc.query();
gs.print("Active Incidents Short Descriptions:");
while(inc.next()){
gs.print(inc.getValue('short_description'));
}
Result: This script will iterate through all active incident records and print the stored short_description for each one to the console (or script log). Simple, right? But incredibly effective!
Real-World Scenario: Filtering with the IN Operator
getValue() really shines when you’re working with more complex queries or when you need to handle multiple possible values. Let’s say your service desk wants to analyze incidents specifically related to ‘Software’ and ‘Hardware’ categories. You can’t just print them; you need to query them first.
var categoriesToFind = ['Software', 'Hardware']; // Note: ensure 'software' and 'hardware' match actual stored values
var inc = new GlideRecord('incident');
// Using addQuery with 'IN' operator to find records matching any of the categories in our array
inc.addQuery('category', 'IN', categoriesToFind);
inc.query();
gs.print("Incidents in Software or Hardware categories:");
while(inc.next()) {
// We can use getValue() here to grab the number and short description
// for outputting the results of our filtered query.
gs.print(inc.getValue('number') + ' - ' + inc.getValue('short_description') + ' (Category: ' + inc.getValue('category') + ')');
}
Result: This script will output the number, short description, and category of all incidents whose category field is either ‘Software’ or ‘Hardware’. This demonstrates how getValue() helps you retrieve the exact values you filtered for, confirming your query.
The Million-Dollar Question: `getValue()` vs. Dot-Walking
If you’ve spent any time scripting in ServiceNow, you’ve probably seen both inc.getValue('short_description') and inc.short_description (this is called dot-walking). So, which one should you use? And why do both exist? This is a prime interview question and a critical understanding for any ServiceNow developer!
-
inc.short_description(Dot-Walking): This is generally more convenient and often returns the “display value” of the field, especially for reference fields or choice lists. For simple string fields likeshort_description, it often returns the same raw value asgetValue(). However, for reference fields (likeassigned_to),inc.assigned_towould give you the Sys ID of the assigned user, not their name. If you want the display name directly via dot-walking, you’d usually go one step further:inc.assigned_to.name(though this can sometimes lead to extra queries if not careful). -
inc.getValue('short_description'): This method always returns the raw, internal value stored in the database.- For a string field, it’s the string.
- For a number field, it’s the number.
- For a choice list, it’s the internal value (e.g., ‘1’, ‘2’, ‘pending’), not the display label (‘New’, ‘In Progress’, ‘Pending’).
- For a reference field (like
assigned_to), it’s the Sys ID of the referenced record. This is crucial if you need to perform queries or lookups based on that Sys ID. - For a Boolean field, it returns ‘true’ or ‘false’ as a string (or ‘1’/’0′ depending on configuration), not a JavaScript boolean
trueorfalse. You’ll often need to convert this:(inc.getValue('active') === 'true')or(inc.getValue('active') == 1).
When to use getValue()?
- For consistent internal values: When you absolutely need the Sys ID of a reference field for further queries, or the internal value of a choice field for comparisons.
-
Dynamic field names: If the field name you need to retrieve is stored in a variable (e.g.,
var myFieldName = 'priority';), you can’t use dot-walking directly (inc.myFieldNamewon’t work). You *must* useinc.getValue(myFieldName). This is incredibly useful for generic scripts or configurations. -
Avoid unintended lookups: While dot-walking for display values (e.g.,
inc.assigned_to.name) is convenient, it can sometimes trigger extra database lookups if not optimized, especially within loops.getValue()simply grabs what’s already on the current record.
In essence, think of getValue() as the reliable workhorse for getting the “truth” from the database, while dot-walking is often a shortcut that might provide a “display truth” or simplify direct property access. A seasoned developer knows when to use each.
Troubleshooting GlideRecord `getValue()`
-
Field doesn’t exist: If you call
inc.getValue('non_existent_field'), it won’t throw an error directly, but it will returnnull. Always validate that the field you’re asking for actually exists on the table. -
Empty values: If a field is empty,
getValue()will return an empty string ('') ornull, depending on the field type and how it was set. Be prepared to handle these cases in your scripts (e.g., checkingif (inc.getValue('my_field')) { ... }). -
Data type confusion: Remember that even numbers or booleans might be returned as strings. Always explicitly convert if you need to perform mathematical operations or strict boolean comparisons. For instance,
parseInt(inc.getValue('order'))or(inc.getValue('active') === 'true').
Interview Relevance: GlideRecord `getValue()`
An interviewer asking about getValue() vs. dot-walking (e.g., record.field) is trying to gauge your understanding of fundamental ServiceNow scripting principles. They want to know if you grasp:
- The difference between internal stored values and display values.
- How to handle reference fields (Sys IDs vs. names).
- Your awareness of performance implications (minimal for a single call, but can add up in loops).
- Your ability to write robust code that handles dynamic field names.
Being able to articulate these points clearly demonstrates a solid foundation in ServiceNow development.
Client-Side Magic: `getValue()` with g_form
Now, let’s shift our focus from the server to the client-side, right where the user interacts with the form. Here, getValue() takes on a slightly different, but equally crucial, role through the g_form API.
What it Does: Getting Field Values from the Current Form
When you’re writing a client script (an onLoad, onChange, or onSubmit script), g_form.getValue() is your go-to method for fetching the current value of a field on the form the user is looking at. This isn’t querying the database directly; it’s asking the form itself, “What’s in this field right now?”
Basic Usage: On the Form
Let’s say you want to quickly see what value a user has selected in the ‘Category’ field as soon as the form loads or changes. You could use an alert (though in real life, you’d use g_form.showFieldMsg() or console.log() for better user experience):
function onLoad() {
// Alert the current category value when the form loads
alert('The current category is: ' + g_form.getValue('category'));
}
// Or in an onChange script for the 'category' field:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
// Alert the new category value when it changes
alert('You just changed the category to: ' + g_form.getValue('category'));
// Note: newValue variable also holds the new value
}Result: An alert box will pop up displaying the category value. This method is incredibly useful for client-side validations, dynamic UI adjustments, and interactive form behaviors.
Practical Explanations: Client Script Scenarios
g_form.getValue() is the backbone of most client-side interactions:
-
Conditional Visibility: “If the ‘Impact’ is ‘High’, make the ‘Urgency’ field mandatory and visible.”
function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || newValue === '') { return; } if (g_form.getValue('impact') === '1') { // Assuming '1' is the internal value for High g_form.setMandatory('urgency', true); g_form.setVisible('urgency', true); } else { g_form.setMandatory('urgency', false); g_form.setVisible('urgency', false); } } - Auto-population: “Based on the selected ‘Caller’, auto-populate their ‘Location’.” (This would typically involve an `onChange` script calling an `Ajax` call to the server to get the location, but `g_form.getValue()` would get the caller’s Sys ID to pass to the server.)
-
Validation: “Ensure the ‘Planned End Date’ is after the ‘Planned Start Date’.”
function onSubmit() { var startDate = g_form.getValue('planned_start_date'); var endDate = g_form.getValue('planned_end_date'); if (startDate && endDate && startDate > endDate) { g_form.addErrorMessage('Planned End Date cannot be before Planned Start Date.'); return false; // Prevent form submission } return true; }
Just like with GlideRecord, g_form.getValue() for a reference field will return the Sys ID, and for a choice list, it will return the internal value (not the display label). This is consistent behavior that you can rely on.
Troubleshooting g_form `getValue()`
-
Field not on form: If you try to get the value of a field that isn’t present on the current form (e.g., hidden by a UI policy or simply not added to the form layout),
g_form.getValue()will returnnullor an empty string. Always ensure the field is actually accessible on the form. -
Client-side vs. Server-side values: Remember,
g_form.getValue()reflects what’s currently in the form fields. If you save the record and a Business Rule changes a value on the server,g_form.getValue()won’t reflect that change until the form reloads. -
Asynchronous operations: If you’re using
g_form.getValue()to prepare data for an AJAX call to the server, ensure that the data is retrieved *before* the AJAX call is made. This is usually straightforward but can be a trap for new developers.
Interview Relevance: g_form `getValue()`
An interviewer asking about g_form.getValue() wants to know if you can:
- Distinguish between client-side and server-side scripting.
- Write effective client scripts for form validation and dynamic behavior.
- Handle different data types on the client side (especially Sys IDs for reference fields).
It demonstrates your ability to build an interactive and user-friendly experience within ServiceNow.
Time Travel and Date Handling: `getValue()` for Dates
ServiceNow provides specialized objects for handling dates and times: GlideDate for date-only values and GlideDateTime for date and time values. Both of these also feature their own getValue() method, which is critical for consistent date/time manipulation.
GlideDate `getValue()`: Just the Date
The GlideDate object’s getValue() method retrieves the date value stored within the object. It always returns this date in a specific internal format: yyyy-MM-dd. Crucially, this value is in the system’s time zone, which is UTC by default. This consistency is paramount for calculations and database interactions, regardless of the user’s local time zone settings.
var today = new GlideDate(); // Creates a GlideDate object for today's date
gs.print('Today\'s internal date value: ' + today.getValue());
Output Example: Today's internal date value: 2023-10-27 (assuming today is October 27, 2023, and running in UTC).
This method is vital when you need to store or compare dates in a database-friendly, unambiguous format.
GlideDateTime `getValue()`: Date and Time
Similar to GlideDate, the GlideDateTime object’s getValue() method fetches the date and time value. This time, the internal format is yyyy-MM-dd HH:mm:ss, again in the system’s default time zone (UTC).
var rightNow = new GlideDateTime(); // Creates a GlideDateTime object for the current date and time
gs.print('Current internal date and time value: ' + rightNow.getValue());
Output Example: Current internal date and time value: 2023-10-27 15:30:45 (assuming the current time is 3:30 PM and 45 seconds UTC).
This is your go-to when you need precise timestamps for logging, auditing, or time-based calculations in a standardized format.
Practical Explanations: Date/Time Handling
Why bother with getValue() when there are other methods like getDisplayValue() or toString()?
-
Database Consistency:
getValue()provides the format that ServiceNow internally uses for storing and comparing dates/times. If you’re building queries, comparing dates, or setting date values for records, usinggetValue()ensures consistency and avoids time zone conversion issues that can arise from display values. - Calculations: When you need to perform calculations (e.g., finding the difference between two dates, adding days), you often want to work with the raw, consistent values. After performing calculations, you might convert back to a display format.
-
toString()vs.getValue()for GlideDateTime: The documentation correctly states thattoString()forGlideDateTimeis equivalent togetValue(). Both return the date and time inyyyy-MM-dd HH:mm:ssformat in the system time zone (UTC). So, if you’re working withGlideDateTime, you can use either for this specific purpose. However, it’s good practice to understand thatgetValue()is part of a broader pattern across different APIs, making it a more universal concept.var customGDT = new GlideDateTime("2024-01-15 10:30:00"); gs.print('getValue() result: ' + customGDT.getValue()); gs.print('toString() result: ' + customGDT.toString());You’ll notice both outputs are identical.
Troubleshooting GlideDate/GlideDateTime `getValue()`
-
Time Zone Confusion: Always remember that
getValue()returns the date/time in the system’s time zone (UTC by default). If you need to present it to a user in their local time zone, you’ll need to usegetDisplayValue()or explicitly convert it. Mixing up system and user time zones is a common source of errors. -
Date vs. DateTime: Be mindful if you’re using
GlideDateorGlideDateTime.GlideDate.getValue()won’t include time components, even if the source field had them. If you need time, useGlideDateTime. -
Parsing Inputs: If you’re initializing a
GlideDateorGlideDateTimeobject with a string, ensure the string format is one that ServiceNow can parse correctly (e.g., ‘YYYY-MM-DD HH:MM:SS’ or ‘YYYY-MM-DD’). Incorrect formats can lead to invalid date objects, and `getValue()` will then return unexpected results or null.
Interview Relevance: GlideDate/GlideDateTime `getValue()`
An interviewer might ask about date/time methods to assess:
- Your understanding of time zone handling in ServiceNow.
- Your ability to differentiate between internal (database) values and display values.
- Your knowledge of how to perform date/time calculations reliably.
- When to choose between
GlideDateandGlideDateTime.
This demonstrates your precision in handling one of the trickiest aspects of enterprise applications.
The Grand Distinction: `getValue()` vs. `getDisplayValue()`
We’ve touched on this a few times, but it’s such a fundamental concept in ServiceNow that it deserves its own spotlight. Many fields in ServiceNow, especially reference fields, choice lists, and date/time fields, have two forms: their internal, stored value and their user-friendly, displayed value.
Consider getValue() as asking, “What’s the unique ID or code for this?” while getDisplayValue() asks, “What does a human user see on the screen for this?”
Examples: Making It Clear
Let’s illustrate this with some concrete examples using a GlideRecord on an Incident:
var inc = new GlideRecord('incident');
inc.addQuery('number', 'INC0010001'); // Assuming INC0010001 exists and is assigned
inc.query();
if (inc.next()) {
// Reference Field (e.g., Assigned To)
gs.print('Assigned To (getValue): ' + inc.getValue('assigned_to')); // Output: sys_id of the user
gs.print('Assigned To (getDisplayValue): ' + inc.getDisplayValue('assigned_to')); // Output: Name of the user (e.g., "Abel Tuter")
// Choice List Field (e.g., State)
gs.print('State (getValue): ' + inc.getValue('state')); // Output: Internal value (e.g., '1', '2', '-5')
gs.print('State (getDisplayValue): ' + inc.getDisplayValue('state')); // Output: Display label (e.g., 'New', 'In Progress', 'Resolved')
// Date/Time Field (e.g., Opened At)
gs.print('Opened At (getValue): ' + inc.getValue('opened_at')); // Output: yyyy-MM-dd HH:mm:ss (UTC)
gs.print('Opened At (getDisplayValue): ' + inc.getDisplayValue('opened_at')); // Output: User's localized date/time (e.g., "10/27/2023 3:30:45 PM EDT")
// Simple String Field (e.g., Short Description)
gs.print('Short Description (getValue): ' + inc.getValue('short_description')); // Output: The actual string
gs.print('Short Description (getDisplayValue): ' + inc.getDisplayValue('short_description')); // Output: The actual string (often the same)
}When to Use Which?
-
Use
getValue()when:- You need the unique identifier (Sys ID) of a referenced record for querying, setting, or comparing.
- You need the internal numerical or string value of a choice field for logical comparisons or database storage.
- You need a consistent, system-time-zone-based date/time value for calculations or database operations.
- You’re dynamically retrieving field names.
- You need to avoid potential extra database queries that
getDisplayValue()or dot-walking might trigger for display names.
-
Use
getDisplayValue()when:- You need to show human-readable text to users (e.g., in alerts, messages, logs, reports).
- You’re integrating with external systems that expect the display name rather than an internal ID.
Understanding this distinction is a hallmark of a proficient ServiceNow developer. It’s not about one being “better” than the other; it’s about choosing the right tool for the specific job at hand.
Wrapping It Up: Your `getValue()` Toolkit
The getValue() method, in its various forms, is undeniably a cornerstone of ServiceNow development. Whether you’re fetching raw data from the database, grabbing user input from a form, or ensuring consistent date/time handling, getValue() provides a reliable and precise way to extract the information you need.
We’ve seen how it works differently yet consistently across GlideRecord, g_form, GlideDate, and GlideDateTime. We’ve tackled the crucial difference between getValue() and getDisplayValue(), a concept that will save you countless hours of debugging and make your scripts much more robust. We’ve even thought about those interviewers and how demonstrating this knowledge can set you apart.
So, the next time you find yourself needing to pull a piece of data in ServiceNow, pause for a moment. Ask yourself: “Do I need the internal, stored value, or the user-friendly display value?” More often than not, getValue() will be your answer for the former, leading you to cleaner code and a deeper understanding of the platform. Keep scripting, keep learning, and happy ServiceNow’ing!