You are on page 1of 19

Which will run first client script or UI policy?

UI Policies execute after Client Scripts. If there is conflicting logic between a


Client Script and a UI Policy, the UI Policy logic applies.

Can we write script in UI policy in ServiceNow?


Yes you can write the script in the UI policies but it is not considered as a
BEST Practice. If you want to make a fields as Mandatory or Read Only or Visible
then go for UI Policy and add the appropriate UI Action other than that if you want to
perform any Form Validations then go for Client Script.

g_form Methods
 Access GlideForm methods using the g_form global object

o g_ form. <method name> (parameter information) ;

=> Syntax

 Examples
 g_form. setValue ('impact ', 1);
 g_form.showFieldMsg( state' , 'Change is waiting approval', '
info');

Commonly used g_form method examples


 Draw attention to an area on the
form: flash(), showFieldMsg()
 Get field information: getValue(), getReferenceO
 Change a field value: setValue(), clearValue()
 Change a choice list: addOption(), clearoptions()
 Get form information: getSections(), isNewRecord()
 Form actions: addlnfoMessage(), clearMessages()

GlideForm methods are only used client-


side.
Examples:

 g_form.addlnfoMessage() — displays an informational


message at the top of a form.
 g_form.addOption() — adds an option to the end of a Choice
list.
 g_form.clearMessages() — removes messages previously
added to the form.
 g_form.clearoptions() — removes all options from a Choice
list.
 g_form.clearValue() — clears a field's value.
 g_form.flash() — flashes a field's label to draw attention to it.
 g_form.getReference() — retrieves a reference object from
the database.
 g_form.getSections() — returns the elements of a form's
section as an array.
 g_form.getValue() — retrieves a field's value.
 g_form.isNewRecord() — returns true if a record has never
been saved.
 g_form.setValue() — sets a field's value.
 g_form.showFieldMsg() — displays a message under a form
field.

GlideRecord Query Cheat Sheet

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

Can also be used in Client scripts and UI policies.

A standard GlideRecord query follows this format.

var gr = new GlideRecord('incident'); //Indicate the table to query from


//The 'addQuery' line allows you to restrict the query to the field/value pairs specified (optional)
//gr.addQuery('active', true);
gr.query(); //Execute the query
while (gr.next()) { //While the recordset contains records, iterate through them
//Do something with the records returned
if(gr.category == 'software'){
gs.log('Category is ' + gr.category);
}
}

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.

var gr = new GlideRecord('sys_user');


gr.addQuery('name', 'Joe Employee');
gr.query(myCallbackFunction); //Execute the query with callback function//After the server
returns the query recordset, continue here
function myCallbackFunction(gr){
while (gr.next()) { //While the recordset contains records, iterate through them
alert(gr.user_name);
}
}

‘Get’ Query Shortcut (used to get a single GlideRecord)

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.

var gr = new GlideRecord('incident');


gr.get(sys_id_of_record_here);
//Do something with the record returned
if(gr.category == 'software'){
gs.log('Category is ' + gr.category);
}

You can also query for a specific field/value pair. The ‘get’ method returns the first record in the result
set.

//Find the first active incident record


var gr = new GlideRecord('incident');
if(gr.get('active', true)){
//Do something with the record returned
gs.log('Category is ' + gr.category);
}

‘getRefRecord’ Query Shortcut (used to get a single GlideRecord referenced in a


reference field)
The ‘getRefRecord’ method can be used as a shortcut to query a record populated in a reference field
on a record.

var caller = current.caller_id.getRefRecord(); //Returns the GlideRecord for the value populated in the
'caller_id' field
caller.email = 'test@test.com';
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.

//Find all incidents with a priority of 1 or 2


var gr = new GlideRecord('incident');
var grOR = gr.addQuery('priority', 1);
grOR.addOrCondition('priority', 2);
gr.query();
while (gr.next()) {
//Do something with the records returned
if(gr.category == 'software'){
gs.log('Category is ' + gr.category);
}
}

Note that you can also chain your ‘OR’ condition as well, which is usually simpler

//Find all incidents with a priority of 1 or 2


var gr = new GlideRecord('incident');
gr.addQuery('priority', 1).addOrCondition('priority', 2);
gr.query();

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.

//Find all active incident records and make them inactive


var gr = new GlideRecord('incident');
gr.addQuery('active',true);
gr.query();
while (gr.next()) {
gr.active = false;
gr.update();
}

Delete
Delete records by performing a glideRecord query and then using the ‘deleteRecord’ method.

//Find all inactive incident records and delete them one-by-one


var gr = new GlideRecord('incident');
gr.addQuery('active',false);
gr.query();
while (gr.next()) {
//Delete each record in the query result set
gr.deleteRecord();
}

deleteMultiple Shortcut
If you are deleting multiple records then the ‘deleteMultiple’ method can be used as a shortcut

//Find all inactive incidents and delete them all at once


var gr = new GlideRecord('incident');
gr.addQuery('active', false);
gr.deleteMultiple(); //Deletes all records in the record set
addEncodedQuery

CANNOT be used in Client scripts and UI policies! Use ‘addQuery(YOURENCODEDQUERYHERE)’


instead.

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

My encoded query string would be this…


active=true^category=software^ORcategory=hardware

I could build that encoded query string and use it in a query like this…

//Find all active incidents where the category is software or hardware


var gr = new GlideRecord('incident');
var strQuery = 'active=true';
strQuery = strQuery + '^category=software';
strQuery = strQuery + '^ORcategory=hardware';
gr.addEncodedQuery(strQuery);
gr.query();

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

//Find all incidents where the Short Description is empty


var gr = new GlideRecord('incident');
gr.addNullQuery('short_description');
gr.query();

//Find all incidents where the Short Description is not empty


var gr = new GlideRecord('incident');
gr.addNotNullQuery('short_description');
gr.query();

getRowCount
‘getRowCount’ is used to get the number of results returned

//Log the number of records returned by the query


var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
gs.log('Incident count: ' + gr.getRowCount());

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…

//Log the number of records returned by the query


var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
alert('Incident count: ' + gr.rows.length);

setLimit
‘setLimit’ can be used to limit the number of results returned

//Find the last 10 incidents created


var gr = new GlideRecord('incident');
gr.orderByDesc('sys_created_on');
gr.setLimit(10);
gr.query();

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.

//Find the last 10 incidents created


var gr = new GlideRecord('incident');
gr.orderByDesc('sys_created_on');
gr.chooseWindow(10, 20);
gr.query();

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.

//Force an update to all User records without changing field values


var gr = new GlideRecord('sys_user');
gr.query();
while (gr.next()) {
gr.setWorkflow(false); //Do not run business rules
gr.autoSysFields(false); //Do not update system fields
gr.setForceUpdate(true); //Force the update
gr.update();
}

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

User Object Cheat Sheet

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.

GlideSystem User Object


The GlideSystem (gs) user object is designed to be used in any server-side JavaScript (Business
rules, UI Actions, System security, etc.). The following table shows how to use this object and its
corresponding functions and methods.

Function/Method Return Value Usage

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...
}

var isMember = gs.getUser().isMemberOf('Ha

To do this for a user that isn't the currently lo

var user = 'admin';


var group = "Hardware";
if (gs.getUser().getUserByID(user).isMemberO
gs.log( gr.user_name + " is a member of " + gr
}

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…

//This script gets the user's title


gs.getUser().getRecord().getValue('title');

g_user User Object


The g_user object can be used only in UI policies and Client scripts. Contrary to its naming, it is not
truly a user object. g_user is actually just a handful of cached user properties that are accessible to
client-side JavaScript. This eliminates the need for most GlideRecord queries from the client to get
user information (which can incur a fairly significant performance hit if not used judiciously).

g_user Property or Method Return value

g_user.userName User name of the current user e.g. employee


g_user Property or Method Return value

g_user.firstName First name of the current user e.g. Joe

g_user.lastName Last name of the current user e.g. Employee

g_user.userID sys_id of the current user e.g. 681ccaf9c0a8016400b98a06818d57c7

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…

//Check to see if assigned to is a member of selected group


var grpName = 'YOURGROUPNAMEHERE';
var usrID = g_form.userID; //Get current user ID
var grp = new GlideRecord('sys_user_grmember');
grp.addQuery('group.name', grpName);
grp.addQuery('user', usrID);
grp.query(groupMemberCallback);

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.

//This script gets the user's title


var gr = new GlideRecord('sys_user');
gr.get(g_user.userID);
var title = gr.title;
alert(title);

EXAMPLE 1: ONCHANGE SCRIPT WITH VALUE SET


View fullsize

Venn Diagram

For this example, we have five fields, Good, Fast, Cheap, and Result.

You know the saying, good, fast, cheap, pick 2?

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.

Client Script: Good onChange

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');
}
}

EXAMPLE 2: OPEN DIALOG WINDOW

I have a good example of a client script opening a GlideDialog window here.

I am just going to show the client script part. In this example, a window pops up on form
load

Client Script: SNE Message

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();
}

EXAMPLE 3: COLOR CODE APPROVAL BUTTONS


View fullsize

Approval Button Color

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.

Client Script: Approval Button Color

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';
}
}

EXAMPLE 4: VERIFY A PHONE NUMBER

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

Pop an alert to the screen if a value is true

Client Script: Awesome Check


Type: onChange
Field: u_awesome_check
Script:
function onChange(control, oldValue, newValue, isLoading)
{
if (isLoading || newValue == '') {
return;
}
if (newValue == 'mike_awesome') {
alert('Yes this is true');
}
}

EXAMPLE 6: ADJUST SLUSH BUCKET SIZES

There is a good example of adjusting slush bucket sizes from the forums.

function onLoad(){

var varName = 'YOUR_VARIABLE_NAME_HERE';

var height = '10'; //Optional

var width = '250'; //Optional

//Get the left and right bucket input elements

var leftBucket = $(varName + '_select_0');

var rightBucket = $(varName + '_select_1');

if(height && g_form.getControl(varName)){

//Adjust the bucket length (default is 18)

leftBucket.size = height;

rightBucket.size = height;

if(width && g_form.getControl(varName)){


//Adjust the bucket width (default is 340)

leftBucket.style.width = width;

rightBucket.style.width = width;

//Fix the expanding item preview issue

$(varName +
'recordpreview').up('td').setAttribute('colSpan', '3');

Use Field Styles for setting other field sizes.

EXAMPLE 7: CALLBACK FUNCTION

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.

Example: without a callback (don't do this)

Client Script: Set VIP

When: onChange

Field: caller_id
function onChange(control, oldValue, newValue, isLoading)
{

var caller = g_form.getReference('caller_id');

if (caller.vip == 'true')

alert('Caller is a VIP!');

Example: with a callback (recommended)

Client Script: Set VIP

When: onChange
Field: caller_id

function onChange(control, oldValue, newValue, isLoading)


{
var caller = g_form.getReference('caller_id',
doAlert); // doAlert is our callback function
}
function doAlert(caller) { //reference is passed into
callback as first arguments
if (caller.vip == 'true')
alert('Caller is a VIP!');
}

EXAMPLE 8: GLIDERECORD QUERY

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.

Client Script: Set Version


On Change
Table: Configuration Item
Field Name: Product
Script:

function onChange(control, oldValue, newValue, isLoading,


isTemplate) {

var gr = new GlideRecord('cmdb_ci');


gr.addQuery('sys_id', newValue);
gr.query(setVersion);
}

function setVersion(gr) {
if (gr.next()) {
g_form.setValue('version', gr.u_version);
}
}

EXAMPLE 9: REMOVE OPTION FROM CHOICE LIST

This is an easy client script. Remove a value from a choice list if something is set.

Client Script: Category Inquiry Remove Impact 1

When: onChange
Field: Category
Script:

function onChange(control, oldValue, newValue, isLoading,


isTemplate) {

if (isLoading || newValue == '') {


return;
}
if (newValue == 'inquiry') {
g_form.removeOption('impact', '1');
}
}
*********getJournalEntry(1) gets the latest entry.

*********getJournalEntry(-1) gets all entries.

You might also like