G Form Methods
G Form Methods
g_form Methods
Access GlideForm methods using the g_form global object
=> Syntax
Examples
g_form. setValue ('impact ', 1);
g_form.showFieldMsg( state' , 'Change is waiting approval', '
info');
I doubt if there’s a single concept in Service-now that is more valuable to understand than how to use
GlideRecord methods to query, insert, update, and delete records in your system. These methods
have a wide variety of uses and are found at the heart of many of the business rules, UI actions, and
scheduled job scripts that are essential to tie together your organization’s processes in your Service-
now instance.
While the content of this post isn’t new information (additional examples can be found on the Service-
now wiki), my aim is to provide a single page of information containing some common examples of
these methods as a reference. This is an excellent page to keep bookmarked!
Note: These methods are designed for use in server-side JavaScript (everything EXCEPT client
scripts and UI policies). In some rare cases, it may be necessary to perform a query from a client-side
javascript (client script or UI policy). The few methods below that can be used in client-side JavaScript
have been noted below.
Query
UPDATE: This same function applies to client-side GlideRecord queries! If at all possible, you
should use an asynchronous query from the client. See this post for details.
Can also be used in Client scripts and UI policies IF YOU ARE GETTING A RECORD BY SYS_ID.
The ‘get’ method is a great way to return a single record when you know the sys_id of that record.
You can also query for a specific field/value pair. The ‘get’ method returns the first record in the result
set.
var caller = current.caller_id.getRefRecord(); //Returns the GlideRecord for the value populated in the
'caller_id' field
caller.email = '[email protected]';
caller.update();
‘OR’ Query
The standard ‘addQuery’ parameter acts like an ‘and’ condition in your query. This example shows
how you can add ‘or’ conditions to your query.
Note that you can also chain your ‘OR’ condition as well, which is usually simpler
Insert
Inserts are performed in the same way as queries except you need to replace the ‘query()’ line with an
‘initialize()’ line as shown here.
//Create a new Incident record and populate the fields with the values below
var gr = new GlideRecord('incident');
gr.initialize();
gr.short_description = 'Network problem';
gr.category = 'software';
gr.caller_id.setDisplayValue('Joe Employee');
gr.insert();
Update
You can perform updates on one or many records simply by querying the records, setting the
appropriate values on those records, and calling ‘update()’ for each record.
Delete
Delete records by performing a glideRecord query and then using the ‘deleteRecord’ method.
deleteMultiple Shortcut
If you are deleting multiple records then the ‘deleteMultiple’ method can be used as a shortcut
An alternative to a standard query is to use an encoded query to create your query string instead of
using ‘addQuery’ and ‘addOrCondition’ statements. An easy way to identify the encoded query string
to use is to create a filter or a module with the query parameters you want to use, and then hover over
the link or breadcrumb and look at the URL. The part of the URL after ‘sysparm_query=’ is the
encoded query for that link.
So if I had a URL that looked like this…
https://demo.service-now.com/incident_list.do?
sysparm_query=active=true^category=software^ORcategory=hardware
I could build that encoded query string and use it in a query like this…
GlideAggregate
GlideAggregate is actually an extension of the GlideRecord object. It allows you to perform the
following aggregations on query recordsets…
-COUNT
-SUM
-MIN
-MAX
-AVG
//Find all active incidents and log a count of records to the system log
var gr = new GlideAggregate('incident');
gr.addQuery('active', true);
gr.addAggregate('COUNT');
gr.query();
var incidents = 0;
if (gr.next()){
incidents = gr.getAggregate('COUNT');
gs.log('Active incident count: ' + incidents);
}
orderBy/orderByDesc
You can order the results of your recordset by using ‘orderBy’ and/or ‘orderByDesc’ as shown below.
//Find all active incidents and order the results ascending by category then descending by created
date
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.orderBy('category');
gr.orderByDesc('sys_created_on');
gr.query();
addNullQuery/addNotNullQuery
‘addNullQuery’ and ‘addNotNullQuery’ can be used to search for empty (or not empty) values
getRowCount
‘getRowCount’ is used to get the number of results returned
Although ‘getRowCount’ isn’t available client-side, you can return the number of results in a client-side
GlideRecord query by using ‘rows.length’ as shown here…
setLimit
‘setLimit’ can be used to limit the number of results returned
chooseWindow
The chooseWindow(first,last) method lets you set the first and last row number that you want to
retrieve and is typical for chunking-type operations. The rows for any given query result are numbered
0..(n-1), where there are n rows. The first parameter is the row number of the first result you’ll get. The
second parameter is the number of the row after the last row to be returned. In the example below,
the parameters (10, 20) will cause 10 rows to be returned: rows 10..19, inclusive.
setWorkflow
‘setWorkflow’ is used to enable/disable the running of any business rules that may be triggered by a
particular update.
//Change the category of all 'software' incidents to 'hardware' without triggering business rules on
updated records
var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
while(gr.next()){
gr.category = 'hardware';
gr.setWorkflow(false);
gr.update();
}
autoSysFields
‘autoSysFields’ is used to disable the update of ‘sys’ fields (Updated, Created, etc.) for a particular
update. This really is only used in special situations. The primary example is when you need to
perform a mass update of records to true up some of the data but want to retain the original update
timestamps, etc.
//Change the category of all 'software' incidents to 'hardware' without updating sys fields
var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
while(gr.next()){
gr.category = 'hardware';
gr.autoSysFields(false);
gr.update();
}
setForceUpdate
‘setForceUpdate’ is used to update records without having to change a value on that record to get the
update to execute. ‘setForceUpdate’ is particularly useful in situations where you need to force the
recalculation of a calculated field for all records in a table or when you need to run business rules
against all records in a table but don’t want to have to change a value on the records.
This method is often used with ‘setWorkflow’ and ‘autoSysFields’ as shown below.
JavaScript Operators
The following operators can be used in addition to the standard field/value query searching shown
above…
= Field value must be equal to the value supplied. addQuery('priority', '=', 3);
> Field must be greater than the value supplied. addQuery('priority', '>', 3);
< Field must be less than the value supplied. addQuery('priority', '<', 3);
>= Field must be equal to or greater than the value supplied. addQuery('priority', '>=', 3);
<= Field must be equal to or less than the value supplied. addQuery('priority', '<=', 3);
!= Field must not equal the value supplied. addQuery('priority', '!=', 3);
STARTSWITH Field must start with the value supplied. The example shown on addQuery('short_description', 'STARTSWITH', 'Error');
the right will get all records where the short_description field
starts with the text 'Error'.
ENDSWITH Field must end with the value supplied. The example shown on addQuery('short_description', 'ENDSWITH', 'Error');
the right will get all records where the short_description field
ends with text 'Error'.
CONTAINS Field must contain the value supplied anywhere in the field. addQuery('short_description', 'CONTAINS', 'Error');
The example shown on the right will get all records where the
short_description field contains the text 'Error' anywhere in the
field.
DOES NOT Field must not contain the value supplied anywhere in the field. addQuery('short_description', 'DOES NOT CONTAIN', 'Error');
CONTAIN The example shown on the right will get all records where the
short_description field does not contain the text 'Error'
anywhere in the field.
IN Field must contain the value supplied anywhere in the string addQuery('sys_id', 'IN',
provided. '0331ddb40a0a3c0e40c83e9f7520f860,032ebb5a0a0a3c0e2e2204a495526dce
INSTANCEOF Retrieves only records of a specified class for tables which are
extended. For example, to search for configuration items
(cmdb_ci table) you many want to retrieve all configuration addQuery('sys_class_name', 'INSTANCEOF', 'cmdb_ci_computer');
items that are have are classified as computers. The code uses
the INSTANCEOF operator to query for those records
N
o matter what system you’re working in, it is always critical to be able to identify information about the
user who is accessing that system. Being able to identify who the user is, what their groups and/or
roles are, and what other attributes their user record has are all important pieces of information that
allow you to provide that user with a good experience (without giving them information they don’t need
to have or shouldn’t have). ServiceNow gives administrators some pretty simple ways to identify this
information in the form of a couple of user objects and corresponding methods. This article describes
the functions and methods you can use to get information about the users accessing your system.
gs.getUser() Returns a reference to the user object for the currently logged-in user. var userObject = gs.getUser();
gs.getUserByID() Returns a reference to the user object for the user ID (or sys_id) provided. var userObject = gs.getUser().getUserByID('em
gs.getUserName() Returns the User ID (user_name) for the currently logged-in user. var user_name = gs.getUserName();
e.g. 'employee'
gs.getUserDisplayName() Returns the display value for the currently logged-in user. var userDisplay = gs.getUserDisplayName();
e.g. 'Joe Employee'
gs.getUserID() Returns the sys_id string value for the currently logged-in user. var userID = gs.getUserID();
getFirstName() Returns the first name of the currently logged-in user. var firstName = gs.getUser().getFirstName();
getLastName() Returns the last name of the currently logged-in user. var lastName = gs.getUser().getLastName();
getEmail() Returns the email address of the currently logged-in user. var email = gs.getUser().getEmail();
getDepartmentID() Returns the department sys_id of the currently logged-in user. var deptID = gs.getUser().getDepartmentID();
getCompanyID() Returns the company sys_id of the currently logged-in user. var companyID = gs.getUser().getCompanyID(
getCompanyRecord() Returns the company GlideRecord of the currently logged-in user. var company = gs.getUser().getCompanyReco
getLanguage() Returns the language of the currently logged-in user. var language = gs.getUser().getLanguage();
getLocation() Returns the location of the currently logged-in user. var location = gs.getUser().getLocation();
getDomainID() Returns the domain sys_id of the currently logged-in user (only used for instances var domainID = gs.getUser().getDomainID();
using domain separation).
getDomainDisplayValue() Returns the domain display value of the currently logged-in user (only used for var domainName = gs.getUser().getDomainDi
instances using domain separation).
getManagerID() Returns the manager sys_id of the currently logged-in user. var managerID = gs.getUser().getManagerID()
Function/Method Return Value Usage
getMyGroups() Returns a list of all groups that the currently logged-in user is a member of. var groups = gs.getUser().getMyGroups();
isMemberOf() Returns true if the user is a member of the given group, false otherwise. Takes either a group sys_id or a group name a
argument.
if(gs.getUser().isMemberOf(current.assignme
//Do something...
}
else{
gs.log( gr.user_name + " is NOT a member of
}
gs.hasRole() Returns true if the user has the given role, false otherwise. if(gs.hasRole('itil')){ //Do something... }
gs.hasRole() Returns true if the user has one of the given roles, false otherwise. if(gs.hasRole('itil,admin')){
//If user has 'itil' OR 'admin' role then Do som
}
hasRoles() Returns true if the user has any roles at all, false if the user has no role (i.e. an ess if(!gs.getUser().hasRoles()){
user). //User is an ess user...
}
It is also very simple to get user information even if the attribute you want to retrieve is not listed
above by using a ‘gs.getUser().getRecord()’ call as shown here…
g_user.hasRole() True if the current user has the role specified, false otherwise. ALWAYS returns true if the user has the 'admin' role.
Usage: g_user.hasRole('itil')
g_user.hasRoleExactly() True if the current user has the exact role specified, false otherwise, regardless of 'admin' role.
Usage: g_user.hasRoleExactly('itil')
g_user.hasRoles() True if the current user has at least one role specified, false otherwise.
Usage: g_user.hasRoles('itil','admin')
It is often necessary to determine if a user is a member of a given group from the client as well.
Although there is no convenience method for determining this from the client, you can get the
information by performing a GlideRecord query. Here’s an example…
function groupMemberCallback(grp){
//If user is a member of selected group
if(grp.next()){
//Do something
alert('Is a member');
}
else{
alert('Is not a member');
}
}
To get any additional information about the currently logged-in user from a client-script or UI policy,
you need to use a GlideRecord query. If at all possible, you should use a server-side technique
described above since GlideRecord queries can have performance implications when initiated from a
client script. For the situations where there’s no way around it, you could use a script similar to the
one shown below to query from the client for more information about the currently logged in user.
Venn Diagram
For this example, we have five fields, Good, Fast, Cheap, and Result.
Here is an example of a client script for this scenario. Note that I use comments '//' to explain
the client script.
I wrote this just for the change of the Good field. However you probably would also want
this for the fast and cheap fields. That means you would need to also add scripts for those
scenarios. This is one of the drawbacks of client scripts.
When: onChange
onChange of field: u_good
Script:
function onChange(control, oldValue, newValue, isLoading,
isTemplate) {
//If the form is loading or the new value of the
changing field is empty exit the script
if (isLoading || newValue == '') {
return;
}
//If Good is true, cheap is true, and fast is true,
good luck
if(newValue == 'true' && g_form.getValue('u_cheap') ==
true && g_form.getValue('u_fast') == true) {
//Set the result field on the form.
g_form.setValue('u_result', 'They are dreaming');
}
//repeat for the other scenarios
else if (newValue == 'true' &&
g_form.getValue('u_cheap') == true &&
g_form.getValue('u_fast') == false) {
g_form.setValue('u_result', 'Will take time to
deliver');
}
else if (newValue == 'false' &&
g_form.getValue('u_cheap') == true &&
g_form.getValue('u_fast') == true) {
g_form.setValue('u_result', 'Not the best quality');
}
else {
g_form.setValue('u_result', 'Who knows');
}
}
I am just going to show the client script part. In this example, a window pops up on form
load
function onLoad() {
//Call a UI Page to Display on load.You have to create
the UI Page separately
var gDialog = new GlideDialogWindow('sne_message');
gDialog.setTitle('ServiceNowElite.com Message');
gDialog.setSize(700,700);
gDialog.render();
}
I use this one often. Color code the approval buttons so that they are easier to notice.
It is tempting to use this for many color changes in ServiceNow. How use Field
Styles instead as much as possible.
When: onLoad
Script:
function onLoad() {
var approveButton = document.getElementById('approve');
var rejectButton = document.getElementById('reject');
if (approveButton) {
approveButton.style.background='green';
approveButton.style.color='white';
}
if (rejectButton) {
rejectButton.style.background='red';
rejectButton.style.color='white';
}
}
Before ServiceNow version Dublin was released, I used this to verify a phone number format.
Dublin has new phone number fields.
However it is a good example of regex function. If you are not familiar with regular
expressions, here are some explanations of what regular expressions.
Client Script: Verify Number
Type: onChange
Field: u_phone_number
Script:
function onChange(control, oldValue, newValue, isLoading)
{
if (isLoading || newValue == '') {
return;
}
var tempValue = newValue;
//Use Regular Expressions to verify number
var phoneRegex1 = /^\d{3}-\d{3}-\d{4}$/;
var phoneRegex2 = /^(800|866|877)/;
var phoneRegex3 = /^(1{3}-1{3}-1{4}|2{3}-2{3}-2{4}|3{3}-
3{3}-3{4}|4{3}-4{3}-4{4}|5{3}-5{3}-5{4}|6{3}-6{3}-6{4}|
7{3}-7{3}-7{4}|8{3}-8{3}-8{4}|9{3}-9{3}-9{4}|0{3}-0{3}-
0{4})$/;
if (tempValue.match(phoneRegex1) && !
tempValue.match(phoneRegex2) && !
tempValue.match(phoneRegex3)) {
return;
}
else {
g_form.setValue('mobile_number', '');
alert('Phone number must be in format XXX-XXX-XXXX and
must not start with 800, 866, or 877.');
}
}
EXAMPLE 5: ALERT
Alert Example
There is a good example of adjusting slush bucket sizes from the forums.
function onLoad(){
leftBucket.size = height;
rightBucket.size = height;
leftBucket.style.width = width;
rightBucket.style.width = width;
$(varName +
'recordpreview').up('td').setAttribute('colSpan', '3');
Callback functions make JavaScript far more flexible than it would be otherwise.
Typical functions work by taking arguments as input and returning a result. Functions take
an input and return an output.
Javascript callback functions are different. Instead of waiting for a function to return that
result, you can use a callback to do this asynchronously. This not only helps with
performance, it strongly encouraged to use callback functions and asynchronous
programming.
When: onChange
Field: caller_id
function onChange(control, oldValue, newValue, isLoading)
{
if (caller.vip == 'true')
alert('Caller is a VIP!');
When: onChange
Field: caller_id
To learn all about client script GlideRecord queries, check out the ServiceNow wiki article.
These are limited glide record queries you can use to make server-side database queries. They
use callback functions to do this. I always suggest using business rules instead for these, but
sometimes I can't convince people to do that.
It is better to use a GlideAjax query than a GlideRecord query. There is a good example in
the wiki for that.
function setVersion(gr) {
if (gr.next()) {
g_form.setValue('version', gr.u_version);
}
}
This is an easy client script. Remove a value from a choice list if something is set.
When: onChange
Field: Category
Script: