SN-SSNF-M010 Scripting in ServiceNow Fundamentals
SN-SSNF-M010 Scripting in ServiceNow Fundamentals
Scripting in ServiceNow
Fundamentals
participant guide
© COPYRIGHT 2019 SERVICENOW, INC. ALL RIGHTS RESERVED.
ServiceNow provides this document and the information therein “as is” and ServiceNow
assumes no responsibility for any inaccuracies. ServiceNow hereby disclaims all warranties,
whether written or oral, express or implied by law or otherwise, including without
limitation, any warranties of merchantability, accuracy, title, non-infringement or fitness
for any particular purpose.
In no event will ServiceNow be liable for lost profits (whether direct or indirect), for
incidental, consequential, punitive, special or exemplary damages (including damage to
business, reputation or goodwill), or indirect damages of any type however caused even if
ServiceNow has been advised of such damages in advance or if such damages were
foreseeable.
TRADEMARKS
ServiceNow and the ServiceNow logo are registered trademarks of ServiceNow, Inc. in the
United States and certain other jurisdictions. ServiceNow also uses numerous other
trademarks to identify its goods and services worldwide. All other marks used herein are
the trademarks of their respective owners and no ownership in such marks is claimed by
ServiceNow.
Application Scope
JavaScript in ServiceNow
Scripting Resources
ServiceNow provides the ability to customize an instance using JavaScript (based on Mozilla Rhino).
JavaScript, popularized by Yahoo, is the most prevalent scripting language on the web. It is object-
oriented, runs within a browser, and does not need a license.
The JavaScript engine used to evaluate scripts in ServiceNow supports the ECMAScript5 standard
and is based upon Rhino version 1.7 R5.
• ServiceNow is continually evolving, what you scripted in the past might not
need to be scripted now
• Easier to debug and fix configuration changes after an upgrade
• Make sure a script is really needed
– How business critical is the requirement?
– Will an ACL perform what you need instead?
– Can you achieve 90% of your requirements via configuration changes instead of
scripting?
• Consider ways of customizing without scripting
The list of examples shown above is representative of typical uses for scripting. There are, of course,
no limits as to what one can do with JavaScript in ServiceNow. It all comes down to your
requirements!
X2
upgrades
• Is customization necessary?
• System treats the Active field as
Update Exempt • Modify the baseline record
In the past, the best practice • Review and revert the skipped
strategy for updating baseline Customized Records do not file after an upgrade
scripts was: get functionality updates
• Make a copy of the record you
want to update ServiceNowis always trying to
Original Inactiv e Record make the upgrade process easier.
• Make the original record inactive Adopting this process will help
• Make changes to the script in the Customized Record with future upgrades to your
copy instance.
Releases: H I J K L
The phrase “Modify a baseline script and you own it.” strengthened the copy, deactivate, and
change the copy process. The strategy was validated when the number of skipped files were
reduced after an upgrade. The original record, other than changing the value of the Active field,
was still the same and it was upgraded. Upgraded baseline files and fewer skipped files was seen as
a good thing.
If you are interested in learning more about Excluding a field from an update, see ServiceNow's
Product documentation for additional information.
Baseline, the admin role has access to all platform features, functions, and data, regardless of
security constraints. Grant this privilege carefully! If you have sensitive information such as private
HR records, ServiceNow recommends granting a custom admin role to an administrator who will
maintain that application.
IMPORTANT
Specific admin roles do not change the access level and behavior of the admin role, which
grants general administrative privileges across the platform.
The Syntax Editor is enabled baseline for new instances. For upgraded instances, a System
Administrator must activate the Syntax Editor [com.glide.syntax_editor] plugin.
Application Scope
JavaScript in ServiceNow
Scripting Resources
Comments will help you, future you, coworkers, and the next administrator understand the code.
Comments will not affect the code’s execution.
When writing scripts, you cannot choose a JavaScript reserved word as a variable name.
While editing a script, Context-Sensitive Help can be invoked by using the following keystrokes at
the cursor location:
• Ctrl + Space (both Mac/Windows)
• . (a period)
Suggestions are context-sensitive relative to the cursor's current position and are filtered based on
API type. For example, when working on a server-side script, only suggestions from server-side APIs
display. When working on a client-side script, only suggestions from client-side APIs display.
Use any one of these strategies to insert a suggested element into your script.
• Highlight an element in the list using the arrow keys on your keyboard, then press the <Tab> or
<Enter> key.
• Continue typing until the element becomes highlighted, then press the <Tab> or <Enter> key.
• Double-click an element in the list.
• Properties assigned to a locally declared object are also included in the list of
suggestions
Field type
IMPORTANT
• If the keyboard language is different from the instance language, you may experience
unexpected behavior.
• Context-Sensitive Help is disabled for XML fields and UI Actions.
• Suggestions provided by Context-Sensitive Help are part of the Scoped Application API.
If an element does not appear in the list of suggestions, simply continue typing the
element’s name. Context-Sensitive Help turns off when the text being entered no
longer matches any suggestions in the list.
Format Code – applies the proper indentation to the script. Use the shortcut Ctrl/Cmd A,
Shift + Tab to quickly format script.
Replace – replaces the next occurrence of a string in the script. Use the Find Next and Find
Previous icons to jump to other occurrences of the string in the script. Confirmation will be
needed.
Replace All – replaces all occurrences of a string in the script. No confirmation is needed.
Search – highlights all occurrences of a search term in the script. Locates the first occurrence.
Toggle Full Screen Mode – expands/contracts the script field to use the full form view for
easier editing.
When the Syntax Editor is off, a Go to line button appears in the toolbar. To use the button:
1. Select it.
2. Enter a line number.
3. Press <Enter> on your keyboard. The cursor will appear at the beginning of that line in the
script.
System Administrators can disable the editor for all users regardless of user preference by setting
the glide.ui.javascript_editor property to false.
To uncomment code:
1. Highlight the code to be made active.
2. Select the Toggle Comment button. The forward slashes at the beginning of each line of code
will disappear.
Multiple lines of code can also be commented out by enclosing the selected block with the /* and
*/ characters.
The Syntax Editor applies auto-indentation to code as it is written. Select the Format Code icon to
re-apply indentation if needed.
Keyboard commands can also be used to quickly format your code. (Can be used in all scripting
fields across the platform.)
1. Ctrl-A/Cmd-A (select all)
2. Shift-Tab (format code)
The Replace and Replace All features can also search for text specified with a regular expression.
Regular expressions must be bracketed by the '/' character. Example, the regular expression
/g_[a-r]{4}/ would also find the string g_form.
The Search feature can also locate text specified with a regular expression. Regular expressions must
be bracketed by the '/' character. Example, the following regular expression /g_[a-r]{4}/,
would also find the string g_form.
Once configured, the trigger seldom changes whereas scripts under development change frequently.
To have more space for the script, select the Toggle Full Screen Mode button to maximize the
Syntax Editor. Select the button again to restore the Syntax Editor to its default size.
For example, in the Syntax Editor, typing the word for followed by pressing the <Tab> key on your
keyboard results in the following insertion at the cursor's position:
Value in the
Comments field
used by the help
macro
Navigate to System Definition > Syntax Editor Macros to create new or edit existing Editor Macros.
Name – macro keyword users type to insert the macro text. (Do not use special characters like
period and quotes)
Application – identifies the scope of the macro.
Comments – provide a description of the macro. Will be used in the help macro output.
Text – full macro text that replaces the name in the editor when the macro is used.
IMPORTANT
Notice the Syntax Editor is not available for the Text field. You are responsible for the
accuracy of your macros.
As with all programming editors and tools, the Syntax Checker cannot find all errors in a script.
Any valid JavaScript will pass the Syntax Check even if the code does not do what you intended.
Note: Some script types will save with syntax errors (Workflow scripts) and others will not.
The system automatically checks for syntax errors as you type in any script field. To view error or
warning details, hover over the red or yellow circles in the sidebar beside the line number, or the
underlined script in the Syntax Editor.
If you cannot locate an error in the statement called out by the Syntax Checker, look at the
preceding line(s) of code.
This feature can be turned off by selecting the Toggle Syntax Check icon.
Application Scope
JavaScript in ServiceNow
Scripting Resources
Favorites
Minimize/Maximize
Navigator Edit Favorites
The Application Navigator provides links to all applications and modules in the ServiceNow platform.
• All applications – all applications and modules are displayed. Double-click the All applications icon for
expand/collapse all functionality.
• Favorites – only items identified as favorites are displayed. Favorites are configured on a per user basis.
When the star icon to the right of an application is selected, all the modules under the application are listed
as favorites.
• Your history – list of most recently accessed items. System Administrators can increase/decrease the
number of records pulled by setting the value of the glide.ui.nav.history_length system property. Baseline,
the initial number of records is 30.
Select the Minimize/Maximize Navigator button to collapse or expand the Application Navigator. Hover over the
icons to display an item’s full name when the Navigator is minimized.
Select Edit Favorites to customize items in the Favorites list.
TIPS FROM THE FIELD
• Save a record as a Favorite by selecting Create Favorite on the record’s Context menu or by
dragging the record from a list to your list of favorites.
• Save a list as a Favorite by selecting Create Favorite on the list's Context menu or by dragging a
breadcrumb condition to your list of favorites.
• If you forget to create a favorite, check Your history for recently accessed items.
• Add the Updated column to a list to sort the list by the most recently edited scripts.
• Add the Updated by column to a list to easily find scripts updated by a specific person.
• Search for the element by 'Name' using the Go to search field at the top of a list.
o mySearchString (no leading or trailing characters) – does a ">=" search (like "starts with" but
includes everything after the search string alphabetically also).
o *mySearchString – does a "contains" search.
o mySearchString% – does a "starts with" search.
o %mySearchString – does an "ends with" search.
A user can achieve the same result by selecting Configure > All from a form's Context Menu, but by
using the command in the Application Navigator’s Filter navigator field you do not have to be on that
form to get to the lists of different configuration records.
• Lab 1.1
– Time: 15-20m
– Using the Syntax Editor
• Practice using the Syntax Editor to understand how scripts are
recorded
• Lab 1.2
– Time: 5-10m
– Syntax Checking
• Practice with the Syntax Checker to catch errors
Lab Summary
You will achieve the following:
• Practice using the Syntax Editor in preparation for writing scripts in ServiceNow.
A. Preparation
1. Navigate to Self-Service > Knowledge on the Application Navigator.
4. You are asked questions throughout the lab exercises to test your knowledge. Do
your best to answer them on your own. Refer to the document if you require
assistance or would like to simply confirm your answers.
Note: When you create a Client Script, you will see this message:
This feature disables items that can cause issues with the platform. You can use these
scripting techniques by following the instructions in the message. You should not need to
make this change for this course.
4. Enter Lab 1.1 Using the Syntax Editor in the Name field.
9. Save the script by selecting the Save button ( ) on the Syntax Editor toolbar
10. Turn off syntax highlighting by selecting the Toggle Syntax Editor button ( ).
What differences do you notice in the Syntax Editor?
_____________________________________________________________________
_____________________________________________________________________
11. Select the same icon to turn syntax highlighting back on.
c) Type Two in the With field then press <enter> on your keyboard.
e) Select Yes when prompted to replace the number 2 in property2 with the word
Two.
b) Type Third in the Replace field then press <enter> on your keyboard.
c) Type third in the With field then press <enter> on your keyboard.
14. Select the Update button on the Header bar to save the script and exit the form.
TIP FROM
THE FIELD:
You can use the Filter
navigator to locate
3. Select Submit. the Client Scripts
module. However,
4. Open the Lab 1.1 Using the Syntax Editor Client Script. Place take a look at the
the cursor on a new line below the existing script. Your history tab (
). Is your Client Script
5. Test the 'try/catch' macro by typing try and pressing the available? This
<tab> key on your keyboard. provides a direct link
to the record and
6. Did the macro display? saves you some
typing.
(If not, confirm the Name is correct in the Syntax Editor
Macro record you created in step-2 and re-test.)
a) Review the description for the try macro. Where did the value come from?
____________________________________________________________
Challenge: What Syntax Editor Macro records can you think of to create? What scripts
do you write multiple times that you would want automated?
___________________________________________________________________
___________________________________________________________________
Lab Completion
Good Job! You have practiced using some of the Syntax Editor features and have created and
used Editor Macros.
Lab Summary
You will achieve the following:
• Practice with the Syntax Checker to determine which types of errors the checker catches.
_____________________________________________________________________
7. Hover the mouse over the orange and red underlines in the script to read the
warning and error messages.
9. Did the Syntax Checker find all the errors in the script? Which error(s) were not
found?
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
Lab Completion
You have practiced Syntax Checking and understand not all errors are caught.
Application Scope
JavaScript in ServiceNow
Scripting Resources
Hu man
Security Hu man
Resources Security
R esources
Su pplier
Su pport Su pplier
Su pport
Baseline applications provided by ServiceNow (e.g. Incident, Service Catalog, Service Portal, etc…),
as well as any custom application built prior to the Fuji release are in the Global scope. It is difficult
to protect/isolate application data in the Global scope.
Artifacts are the application files in an application. Examples include, but are not limited to, Tables,
Access Controls, Email Notifications, Data Policies, Client Scripts, Business Rules, Script Includes, etc.
Application developers specify an application scope when they create a new application. They can
also specify what parts of an application are accessible to other applications from:
• The Custom application record.
• Each application Table record.
For example, suppose you create a Travel & Expanse Management application. By default, the
application can access and change its own tables and business logic, but other applications in the
platform cannot unless you grant them explicit permission to do so.
The application scope prevents naming conflicts and allows the contextual development
environment to determine what changes, if any, are permitted.
Applications in the Global scope do not append a unique namespace identifier to the application
name.
Built-in limitations prevent developers from updating artifacts while in a different scope. This
protects the application from inadvertent modifications.
Application Scope
JavaScript in ServiceNow
Scripting Resources
• Provide classes and methods that can be used in scripts to define the
functionality of the platform
• A few examples:
Client-side Classes Server-side Classes
GlideAjax GlideAggregate
GlideForm GlideDateTime
GlideList GlideElement
GlideRecord GlideRecord
GlideUser GlideSystem
spModal JSON
Workflow
Classes are grouped by those used for client-side scripts, REST APIs, global server scripts,
and scoped server scripts.
More classes are available for use in scripts and new ones are constantly being developed. It is
important to stay current on what has changed from release to release.
• Visit ServiceNow's official Developer site to see the list of available API classes and methods,
definitions on what they do, instructions on how to use them, as well as sample scripts written
by ServiceNow developers.
• Visit ServiceNow's official Documentation site to review API release notes.
Another thing you want to consider is the version of your instance. Make sure the documentation
you are looking at is the version of your instance.
In the API documentation, you will find links to scope application, legacy application, and instance
versions within the documentation.
ES5 Standards Mode is the default mode when creating new scoped scripts. It supports
ECMAScript5 syntax, extensions, and features, including:
• The 'use strict' declaration.
• Control over extensibility of objects.
• Get and set properties on objects.
• Control over write-ability, configurability, and innumerability of object properties.
• New Array and Date methods.
• Native JSON support.
• Support for modern third-party libraries such as lodash.js and moment.js.
Application Scope
JavaScript in ServiceNow
Scripting Resources
community.servicenow.com
IMPORTANT
Get feedback not only from your internal sources, but from other customer sources as
well.
Join a SNUG near you today. Attending an event is a fantastic opportunity to gain new knowledge
and network with your peers that share a passion for ServiceNow. The benefits of attending a SNUG
are numerous.
• Face-to-face interactions with ServiceNow subject matter experts, product evangelists,
executives and partners.
• Knowledge transfer across diverse organizations, industries, and ServiceNow use cases.
• Connect with and learn from peers while developing professional relationships.
• Insight into upcoming product releases, roadmaps and company updates including sneak
previews into new features and on-going product development.
• Help shape future product direction by providing real-time feedback.
• Access to live customer testimonials, demos and hands on workshops.
• Open forum to discuss ideas, industry trends, challenges and observations.
SNUGs are managed by ServiceNow users just like you. If there is no SNUG in your area, you can
create one!
docs.servicenow.com
Product Documentation provides ServiceNow's official documentation about the platform. Use the
Search documentation field to quickly navigate to the information you are looking for.
In addition to navigating directly to the website, you can also select the Search Product
Documentation link from the Help icon on the banner frame in any instance.
developer.servicenow.com
The ServiceNow Developer Program provides ServiceNow developers with a dedicated program of
free content, technical resources, developer focused training, tools, events, and an online
community for collaboration and sharing.
It is designed to maximize the productivity, effectiveness and efficiency of developers creating value-
added applications and solutions on ServiceNow.
Register for a personal developer instance to practice building, extending and integrating new
applications in a safe sand-box environment.
https://www.servicenowlearninglibrary.com/
The ServiceNow Learning Library provides a cost-effective option to supplement our traditional
training courses with 24/7 access to a wide variety of learning assets designed to enhance learning.
Training ranges from short videos to detailed tutorials that can be paused at any point and
continued later – allowing you to learn on a schedule that aligns with your availability. Mobile-ready
content provides access at any time and from any location.
• Lab 1.3
– Time: 15-20m
– Explore Scripting Resources
• Explore the community website
• Explore the documentation website
• Explore the developer website
Lab Summary
You will achieve the following:
• In this lab, you will practice using various resources to get scripting help.
A. Explore Community
1. In a web browser, navigate to community.servicenow.com .
2. Sign in. If you do not have an account, create one by selecting the SIGN IN/JOIN link.
3. Select the Register button. After requesting an account, continue with the lab.
a) From the Header bar, select Groups > ServiceNow User Groups.
c) Select a ServiceNow User Group from the list that appears below the map.
____________________________________________________________________
a) Select the Search (magnifying glass) icon at the top-right corner of the page.
b) Type Ask Why in the search field and press <Enter> on your keyboard.
_____________________________________________________________________
_____________________________________________________________________
B. Explore Documentation
1. Navigate to ServiceNow's official Product Documentation website:
docs.servicenow.com.
2. Select Madrid.
4. On the left Navigation menu, expand the Features and changes by product
category, expand the Application development release notes, and then expand the
article titled API release notes.
Note: The Now Platform release notes category is where you locate information about new
and updated features made to the platform itself, (this includes changes to Scripting as it is a
function of the platform). The information and number of articles changes from release to
release. This particular API release notes article is a good example of easy to locate
information.
____________________________________________________________________
____________________________________________________________________
6. Use the magnifying glass to search Documentation for the string Useful scripts
a) Type Useful scripts in the Search field at the top-right corner for the page and
press <Enter> on your keyboard.
Note: This article contains links to other articles offering scripts written by ServiceNow
developers. You may want to favorite this webpage so you can explore it when you have more
time.
C. Explore Developer
1. Select the More Sites drop-down menu, followed by Developer Documentation to
navigate to ServiceNow's Developer website (developer.servicenow.com).
Note: The Scoped menu lists documentation for applications in a private scope. These APIs may
behave differently in the Global scope. The Legacy menu lists documentation for legacy
applications in the Global scope.
4. Locate and expand the GlideDateTime category.
__________________________________________________________________
Lab Completion
Good Job! You have really explored some of the ServiceNow resources that are at your
fingertips when you need help scripting.
• Identify the Scope of your script to ensure it only affects the resources in the same
scope
• ServiceNow websites are more than just product documentation; make good use of
the Community
• Join at least one SNUG
Privately scoped scripts only affect resources in the •How often would you use these
same scope
capabilities?
Know where to get scripting help
Discuss: Why, when, and how often would you use the capabilities shown in this module.
GlideRecord Labs
Ev ents
Lab 2.1 Two Simple Client Scripts
Lab 2.2 g_form and g_user
Script Includes
Lab 2.3 Debugging Client Scripts
UI Actions Lab 2.4 Client Scripting with Reference Objects
Flow Designer
Client-side APIs
Client-side Debugging
Reference Objects
Script Versions
• Client Scripts manage the behavior of forms, fields, and lists in real time
– Make fields mandatory
– Set one field in response to another
– Modify choice list options
– Hide/Show form sections
– Display an alert
– Hide fields
– Prohibit list editing
Although modern browsers largely interpret JavaScript the same way, you may still observe browser-
dependent behaviors in client-side scripts.
What to execute
All scripts have a trigger specifying when a script's logic should execute. The trigger configuration
fields depend on the script type.
The Description field is for documenting the script. Include information like who wrote the script,
what business requirement the script is for, and any other pertinent information.
The Messages field is used for internationalizing output to the user. For example, if the script
creates an alert that says Hello World, the string "Hello World" would appear in the Messages field
on its own line. If an entry exists in the sys_ui_message table with the same key but a localized
language, the localized language version is presented to the user even though the script uses the
version from the Messages field.
The Script field is used to script what needs to happen when the conditions in the trigger are met.
Additional information
is required if the Client
Script is triggered by a
field value change or
if it applies to a
specific view of the
form
While on the Client Scripts list, select New to create a new Client Script.
Name – name of the Client Script. Use a standard naming scheme to identify custom scripts.
Table – table the form or list is related to.
UI Type – select whether the script executes for Desktop only, Mobile / Service Portal only, or All
environments.
Type – select when the script runs: onChange, onLoad, onSubmit, or onCellEdit.
Field name – used only if the script responds to a field value change (onChange or onCellEdit); name
of the field to which the script applies.
Application – identifies the scope of the Client Script.
Active – if selected the script is executing in the runtime environment.
Inherited – execute the script for forms from any extending tables when selected.
Global – if Global is selected the script applies to all Views. If the Global field is not selected you
must specify the View.
View – specifies the View to which the script applies. The View field is only visible when Global is
not selected. A script can only act on fields part of the selected form View. If the View field is blank
the script applies to the Default view.
• Use the Order field when multiple Client Scripts for the same table have
conflicting logic
• Executes in order from lowest to highest
• Does not appear on the Client Script form baseline
– Configure the form to add the field
Order is the sequence in which the Client Scripts are executed, from lowest to highest. By
convention, Order numbers contain three digits. For example: 150, 300, or 675.
• Script runs when a form loads and before control is given to the user
• Typically used to manipulate a form's appearance or content on screen
Users do not have the ability to modify form fields while an onLoad() Client Script executes.
No arguments passed to it
For example, a baseline onLoad() Client Script on the Change form marks Standard Change fields
read-only before control is given to the user.
Usually, onLoad() Client Scripts perform client-side-manipulation of the current form or set default
record values.
User saves, submits, or onSubmit( ) Client Scripts execute Record written to database
updates a record
Saldkdf Sdlfjs fd
Users do not have the ability to modify form fields while an onSubmit() Client Script executes.
No arguments passed to it
function onSubmit() {
if(!myCondition) {
return false;
}
else {
//perform some logic here
}
}
An onChange() Client Script watches one field. If two fields need to be watched, a second Client
Script must be configured.
For example, one onChange() Client Script populates the 'Assignment group' field if the value in the
Configuration item [cmdb_ci] field changes, while a second onChange() Client Script populates the
Watch List if the value of the 'Priority' field changes to 1.
5 parameters passed to it
An onChange() Client Script runs when a particular field value changes on the form.
Modify the script to change the behavior if necessary. For example, you might also check to see if
the field value change was due to a template load.
If you create a client-side script for fields on a form, an onCellEdit() Client Script can be used to
ensure data in those fields is similarly controlled in a list.
IMPORTANT
onCellEdit() scripts do not apply to List Widgets on homepages or dashboards.
5 parameters passed to it
You must pass back either true or false in the callback function. If true is passed as a parameter, the
other scripts are executed or the change is committed if there are no more scripts. If false is passed
as a parameter, any further scripts are not executed and the change is not committed.
Example:
function onCellEdit(sysIDs, table, oldValues, newValue, callback) {
var saveAndClose = true;
if(newValue == 6) { //Resolved
alert("You cannot change the state to 'Resolved' from a list");
saveAndClose = false;
}
if (newValue == 7) { //Closed
alert("You cannot change the state to 'Closed' from a list.");
saveAndClose = false;
}
callback(saveAndClose);
}
• Lab 2.1
– Time: 15-20m
– Two Simple Client Scripts
• Practice writing Client Scripts
• Understand the difference between an onLoad() and onCellEdit()
Client Script
Lab Summary
You will achieve the following:
• Write and test two simple Client Scripts. Consider saving the Client Scripts module as
a Favorite before beginning this lab.
• Create an onLoad() Client Script that generates an alert.
• Create an onCellEdit() Client Script to stop Incident records from being set to
Resolved or Closed from a list view.
Replace the existing comment and add the following alert to the function.
TIP FROM
3. Select Format Code to re-align the script. (This is a good THE FIELD:
habit to get into.) The keyboard
shortcut to Format
4. Select Submit. Code starts with
Ctrl+A for Windows
and Cmd+A for Mac
to select all code.
B. Test Your Work Then Shift+Tab to
format the code.
1. Open any Incident record. What happens when the
form loads?
_________________________________________________________________
3. Select OK.
5. Select Save on the form's Context menu to save the record and remain on the form.
_________________________________________________________________
7. Create a new Incident. What happens when the form loads for the new incident? Is
this the behavior you expected?
_________________________________________________________________
c) Select Update.
4. Select Submit.
2. Without opening a record, pick any Incident in the list. Record the current value of
its State field:
_______________________
5. Select OK.
6. Did the Resolved value remain in the State field? Why or why not?
_________________________________________________________________
7. Hold the Shift key down on your keyboard, then select multiple State fields. (The
background of the selected items changes to green.)
8. Double-click any one of the selected State fields, change its value to Closed, and
select Save.
9. Did an alert appear advising you cannot change the State to 'Closed' from a list? If
not, debug and re-test your script.
11. Did the Closed value remain in any of the State fields? Why or why not?
_________________________________________________________________
13. Make the Lab 2.1 onCellEdit Alert Client Script inactive.
Lab Completion
Good job! You have successfully created onLoad() and onCellEdit() Client Scripts. Your testing
efforts helped you to understand how each method works.
Client-side APIs
Client-side Debugging
Reference Objects
Script Versions
In addition to these pre-defined global variables, you also have any local variables you declare in a
script.
Visit developer.servicenow.com for the complete list of available client-side classes and methods.
Object properties are the fields from the currently loaded record.
Object values are the field values when the record is initially loaded.
• Examples
g_form.setValue('impact',1);
g_form.showFieldMsg('state','Change is waiting approval','info');
Examples:
g_form.addInfoMessage() – 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.
• g_form object methods refer to fields by their field name, not their label
• Easy way to locate a field name
– Right-click a field's label
– The field name appears on the Context menu
For example, the first parameter required by the addDecoration() method is a field name.
g_form.addDecoration('String field_name','String icon','String title');
Provide the field name caller_id vs. the field label Caller.
g_form.addDecoration('caller_id','icon-star','preferred member');
Since JavaScript is weakly typed, it is not always necessary to verify data type when scripting. In the
case of the g_form.getValue() method however, you must pay attention to data type or your script
may have unexpected results.
The g_form.getValue() method always returns a string despite the data type of the field. If returning
a number is important, use the g_form.getIntValue() or g_form.getDecimalValue() methods instead.
IMPORTANT
This method cannot retrieve values from the database, it retrieves values from forms even
if the field is not visible in the current view or to the logged in user.
• g_form.getValue('number')
– Returns the field's content exactly as it appears on the form
– The Number [number] field is a text field
Right-click a field's label and select Show – '<field_name>' from the Context menu to confirm a
field's data type.
• g_form.getValue('impact')
– Returns the value of the selection, not the user friendly label
– The Impact [impact] field is a choice list
To see a choice list's values, right-click the field's label and select Show Choice List.
• g_form.getValue('caller_id')
– Returns the sys_id of the referenced record
– The Caller [caller_id] field is a reference field
• The GlideUser API provides useful methods to access information about the
currently logged in user
• Access GlideUser methods using the g_user global object
For the form shown, the g_user object contains the following properties and values for Beth Anglin:
g_user = {
userName: "beth.anglin",
userID: "46d44a23a9fe19810012d100cca80666",
firstName: "Beth",
lastName: "Anglin"
}
getClientData() – returns the session client value previously set with the putClientData() method.
getFullName() – returns the logged in user's first name and last name separated by a space.
hasRole() – returns true if the logged in user has the specified role or has the admin role.
hasRoleExactly() – returns true only if the logged in user has the specified role.
hasRoleFromList() – returns true if the logged in user has at least one role from the passed in list or
has the admin role.
hasRoles() – returns true if the logged in user has any role.
IMPORTANT
DO NOT rely on g_user methods to apply security. Client-side security is easily defeated
using developer tools built into browsers. Access Control or another server-side security
strategy is recommended.
• Lab 2.2
– Time: 20-25m
– g_form and g_user
• Practice writing a Client Script using the g_form and g_user
objects and their methods
Lab Summary
You will achieve the following:
• Practice writing a Client Script using the g_form and g_user objects and their
methods. When this lab is completed you will be able to mark a Cloud Dimensions'
Phase II requirement complete.
Business Problem
At Cloud Dimensions, a Major Incident Manager is responsible for submitting Priority-1 (P1)
Incidents. This ensures the Incident adheres to strict process and communication guidelines.
Twice in the last 6 months, the on-duty Major Incident Manager was not available to perform
this duty and the initial information provided in the record by the IT analyst was not complete.
This created additional havoc when management received incomplete P1 Email Notifications.
Project Requirement
A P1 Incident record is expected to have the following fields populated before it is submitted:
• Category
• Configuration Item
• Assignment group
• Short description
Cloud Dimensions is requesting this functionality be built into the Incident form:
• If the person creating the record is NOT a Major Incident Manager, then the agent
creating a P1 Incident should be prompted to confirm the minimum Major Incident
information is included in the record before it is submitted.
• Instructions on how to handle unavailable mandatory details should be included as
well.
A. Preparation
1. Create a new role for the Major Incident Manager.
c) Select Submit.
2. Create a new Major Incident Manager Group to identify the organization's Major
Incident managers and give the Group the major_inc_mgr Role.
d) Select the Edit button on the Roles Related List and add the major_inc_mgr role
to the list.
e) Select the Edit button on the Group Members Related List and add Beth Anglin,
Christen Mitchell, and Don Goodliffe to the list.
4. Select Submit.
4. What happened to the Incident form when you cancelled the submission? Was the
Incident submitted?
_________________________________________________________________
_________________________________________________________________
5. Modify the confirmation dialog box in the script so the confirmation message
includes the logged in user's first name. Which property do you need to use?
_________________________________________________________________
6. Test the modified script. Was the logged in user's first name included? If not, debug
and re-test.
c) Enter Beth Anglin, Christen Mitchell, or Don Goodliffe in the Search for user
field and select the record when it appears in the drop-down list. The page will
refresh and their avatar will appear on the Header bar.
8. Create a new Incident, populate the mandatory fields, and set both the Impact and
Urgency values to 1-High.
9. Save the record, remain on the form. Did the confirmation message display? Explain
why not:
_________________________________________________________________
_________________________________________________________________
10. Repeat steps 7a-7c to end the impersonation. You should be logged in as the System
Administrator when this step is complete.
11. Make the Lab 2.2 Confirm Major Inc Details Client Script inactive.
Lab Completion
Good job! You have successfully used g_form and g_user methods and properties in a script,
as well as practiced impersonating users to confirm the successful execution of a role based
on specific role conditions.
Client-side APIs
Client-side Debugging
Script Versions
In some cases, more than one debugging strategy may need to be used.
The showFieldMsg() method can also be used to display debugging output next to a specific field.
All users are affected when the addInfoMessage(), addErrorMessage(), and showFieldMsg()
methods are used as everyone sees the output on the form. In a multiple administrator/developer
environment this approach has the potential to be confusing. Consider including code in your
debugging scripts to include your name in the output or to hide the output from other users.
• Include a g_user property in the script to identify yourself in the message. Example:
g_form.addInfoMessage(g_user.firstName + ", the value of caller_id
is: " + g_form.getValue('caller_id'));
• Include a g_user property in combination with an IF statement to display the message only to
you. Example:
if(g_user.userName == 'admin'){
g_form.addInfoMessage("The value of caller_id is: " +
g_form.getValue('caller_id'));
}
• Log file
• Runs on the browser
• Use the jslog() method to send information to the JavaScript Log
jslog( ) output
Follow these steps to open the JavaScript Log (admin users only):
1. Select the System Settings (gear) icon on the Header bar.
2. Turn the JavaScript Log and Field Watcher button on. The JavaScript Log opens at the bottom of the
page (Small, Medium, and Large buttons allow you to select your preferred window size).
3. Create the conditions necessary to test your script.
4. View jslog() messages in the JavaScript Log.
The JavaScript Log appears only for the admin user who opened it; no other users are impacted.
If the JavaScript Log closes, use the JavaScript Log and Field Watcher button on the System Settings menu to
re-open it. It must remain open in order to debug.
The JavaScript Log is only available in Desktop mode; it is not available in the Tablet or Mobile operating
systems.
Any argument passed to the jslog() method appears in the JavaScript Debug window. Such as:
• Strings
• g_form or g_user properties or methods
• Variables
• JavaScript string escape characters such as "\n" (new line) and "\t" (tab).
Use this strategy to look for Client Script issues causing long load times.
Administrators can disable the Response Time Indicator by setting the glide.ui.response_time
property to false.
Try/Catch syntax:
try{
//code to execute goes here
}
catch(err){
//code to deal with error here
}
err is a JavaScript object with properties description, message, name, and number.
You can throw your own error messages for the catch function using the JavaScript throw() function.
Try/catch only traps runtime errors. Using throw() you can also catch user errors such as entering an
invalid data value in a field.
• Lab 2.3
– Time: 20-25m
– Debugging Client Scripts
• Practice debugging a Client Script
Lab Summary
You will achieve the following:
• Debug a Client Script using ServiceNow and JavaScript strategies.
A. Preparation
1. Locate and open the Lab 2.3 Client Script Debugging Client Script for editing.
4. Consider saving the record as a favorite as you will be opening it a few times
throughout the lab. Select Create Favorite on the form's Context menu.
5. Select Update.
2. Without changing the value of the State field, open the drop-down choice list and
make a mental note of the available options.
4. Confirm the Lab 2.3 Client Script Debugging Client Script executed as expected.
Expected Behavior Occurred?
A decoration appeared to the left of the State field
The State's label flashed teal for four seconds
The State choice list options now only include 'New' and 'In ü
Progress'
An Information Message appears at the top of the form confirming ü
the State options removal
2. Use the jslog() method in strategic places to debug your script. If you require
assistance, you can use this script as an example of how to include jslog() messages
in your script.
3. Select Update.
2. Select Developer.
4. Close the System Settings window when you are ready to proceed.
2. Select the Clear log icon ( ) to remove any existing log messages.
3. Select your preferred view (Small, Medium, or Large) so the log messages are visible
at the bottom of your screen.
6. What can you conclude regarding the debugging output currently in the JavaScript
Log?
____________________________________________________________________
Review the State field name in this statement, does it match the field name you
documented in step-7? _________
12. Force your updated script to execute by creating a new Incident. If you closed the
JavaScript Log, re-open it.
15. Confirm the Lab 2.3 Client Script Debugging Client Script executed as expected.
Expected Behavior Occurred?
A decoration appeared to the left of the State field ü
The State's label flashed teal for four seconds ü
The State choice list options now only include 'New' and 'In ü
Progress'
An Information Message appears at the top of the form confirming ü
the State options removal
17. If you answered No to any of these questions in steps 15 or 16, debug and re-test.
19. Review the InfoMessage at the top of the form. Are you the only person who can
see this script output?
____________________________________________________________________
20. Form messages are a good debugging strategy as the results are instantly presented
the top of the form you are testing on. Would this type debugging strategy be best
in a development or production instance?
____________________________________________________________________
3. Examine the built-in debugging provided by the platform below the Impact field.
Correct any errors in the script and re-test until no errors remain.
Hint: You will find the list of available GlideForm methods on developer.servicenow.com very
helpful for this step.
2. Can Beth turn the JavaScript Log and Field Watcher on? Why or why not?
____________________________________________________________________
3. Beth Anglin does not have the 'admin' role and therefore cannot impersonate other
users. Return to the System Administrator, then impersonate Fred Luddy.
____________________________________________________________________
5. Based on this test, what can you conclude regarding the JavaScript Log and Field
Watcher while you are impersonating another user?
____________________________________________________________________
6. End the impersonation. You should be logged in as the System Administrator when
this step is complete.
8. Select Update.
9. If you saved the Client Script as a Favorite at the beginning of the lab, you can
remove it from the list now as you have completed debugging it.
Lab Completion
Well done! You have successfully debugged a script using client-side debugging methods.
Client-side APIs
Client-side Debugging
Reference Objects
Script Versions
When writing client-side scripts, you have access to all form fields and their values. Reference
Object fields exist on forms but the Reference Object record itself is not loaded into the form.
Database
Server
A reference field stores a sys_id for the record it references in the database, but the sys_id is not
shown. The reference field shows the record's display value on the form.
Step 1: Step 2:
Request a record Requested record returned
from the database from the database
recordObj = {
prop1: value1,
prop2: value2,
….
propN: valueN
}
The following occurs when a script requests a record on another table in the database:
1. A client-side script requests a record from the database.
2. The server retrieves the requested record from the database and passes the record back to
the calling client-side script as an object.
3. The callback function logic executes when the object returns from the server.
The g_form.getReference() method runs asynchronously when a callback function is used. When the
record is returned to the calling script, the logic in the callback function executes. If the callback
function is omitted, the g_form.getReference() method runs synchronously.
• Syntax
g_form.getReference(field_name,callback_function)
• Example
In the example shown, the callerInfo() function is called only after the caller_id record is returned
from the server.
function callerInfo(userRecord){
alert("User ID: " + userRecord.user_name + "\nLocked Out:"
+ userRecord.locked_out);
}
Synchronous getReference() method calls lock the form until the requested record is returned from
the database. Asynchronous execution allows users to continue using the form while the method
call executes.
The first example executes synchronously resulting in a poor user experience. getReference()
without a callback function will not run on the Mobile platform.
The second example also executes synchronously and returns only one field's value. The
performance penalty is the same as for the first example.
The third example demonstrates how to make an asynchronous call to the server. While this was
considered to be a best practice for some time, using g_form.getReference retrieves all fields from a
requested GlideRecord. Typically, the client may only need one field. This can have an impact on
performance. This has been included so you are aware of its use. We will discuss a better way later.
• Lab 2.4
– Time: 15-20m
– Client Scripting with Reference Objects
• Practice writing, testing, and debugging a Client Script that works
with Reference Objects
Lab Summary
You will achieve the following:
• Practice using the getReference() method to retrieve records for Reference Objects.
You will write a script to automatically set the Priority, Risk, and Impact to Low if the
Configuration item is 3D Pinball.
4. Select Submit.
3. Are the Priority, Risk, and Impact fields set correctly? Are they read-only? If not,
debug and re-test.
5. Are the Priority, Risk, and Impact fields read-only? Should they be?
_____________________________________________________________
6. Modify the script so the Priority, Risk, and Impact fields are editable if the Configuration
Item is not 3D Pinball. (Script on the next page.)
Lab Completion
Well done! You successfully created a Client Script that required two separate getReference()
calls that executed two different actions when one field changed on the form.
Client-side APIs
Client-side Debugging
Reference Objects
Script Versions
Script versions are available for other script types and are not unique to Client Scripts.
Update Sets do not include every version. If you migrate a script from one instance to another, only
the most recent version of the script is included in an Update Set.
The Versions Related List is visible baseline. In the event it is not, open the record's Context menu
and select Configure > Form Layout. Add Versions to the Selected column and save the change.
Select a
different field
Overwrite the
current value of
the field with
value from the Select to edit
selected version script
Select the Revert to Selected Version button at the top of the form to overwrite the Current Version
record with the Selected Version record.
Select the Save Merge button to save changes made to the Current Version while on the Compare
to Current page.
You can easily undo recent changes to a script by selecting the Revert to this version Related Link to
revert to a previous version.
Discuss: Why, when, and how often would you use the capabilities shown in this module.
GlideSystem
Labs
GlideRecord
Lab 3.1 Incident Resolved / Closed UI Policy
Ev ents
Script Includes
UI Actions
Flow Designer
In the basic case UI Policies do not require scripting. In the example shown, no scripting was
required to:
• Make the Number field read-only.
• Make the Configuration item field mandatory.
• Hide the Priority field.
Client Scripts can also hide fields, show fields, and make fields mandatory. If you can, always use a
UI Policy instead of a Client Script for faster load times and easier maintenance.
IMPORTANT
UI Policies do not run unless their condition is met. In some cases, UI Policies do not have
a condition – these UI Policies execute every time a form loads and/or is changed.
Example:
UI Policy ensures Comments
are mandatory when an
Approval is rejected
g_form.showFieldMsg( )
method used to include
instructions
This example occurs when the baseline Comments mandatory on rejection UI Policy executes.
The Advanced view of the UI Policy form is presented baseline. Select the Default view Related Link
to remove the advanced fields.
There is a basic four step strategy to create a new UI Policy:
1. Configure the UI Policy trigger:
Table – table to which the UI Policy applies.
Application – identifies the scope of the UI Policy.
Active – select the checkbox to make the UI Policy active.
Short description – supply a short explanation of what the UI Policy is for. The value in this
field appears in the debugging information.
Order – the sequence in which UI policies are applied, from lowest to highest. Use when
there are multiple UI Policies for the same table that may contain conflicting logic.
2. Configure the the When to Apply conditions (when the UI Policy will run).
3. Save (not Submit) the record.
4. Configure the UI Policy Actions (what the UI Policy will do):
Field name - field for which the UI Policy applies an action.
Mandatory - how the UI Policy affects the mandatory state of the field.
Visible – how the UI Policy affects the visible state of the field.
Read Only – how the UI Policy affects the read-only state of the field.
IMPORTANT
Although a UI Policy can evaluate any field in a record regardless if it is visible by the end
user, the field specified in a UI Policy Action does need to be present on the form. For
UI11, ensure any field called by a UI Policy exists on the form.
The Condition Builder is not unique to UI Policies; the feature is used across the platform.
IMPORTANT
Conditions are only re-evaluated if a user manually changes a field on the form; if the
change is made by the system it will not be rechecked. Use Data Policies, which are not
scriptable, to manage the mandatory and read-only state of fields for records not changed
on a form.
• Select Run scripts on the Script tab to access the scripting fields
• Can write a script in one or both fields
• UI Policy Scripts execute client-side
Run scripts in UI type – select whether the script executes for Desktop only, Mobile/Service Portal,
only or All environments.
Execute if true – JavaScript executes when the UI Policy Condition tests true.
Execute if false – JavaScript executes when the UI Policy Condition tests false.
The onCondition() function in the appropriate UI Policy script fields is automatically called when the
condition returns true or false.
IMPORTANT
The Reverse if false (located on the 'When to Apply' tab) field must be selected in order for
the Execute if false script to execute.
• Must be enabled/disabled
– System Diagnostics > Session Debug > Debug UI Policies
– System Diagnostics > Session Debug > Disable UI Policies Debug
• Output appears in the JavaScript Log window
• Shows evaluation of condition and script processing
UI Policy Action Processing Condition Evaluation Result Individual Condition Line Item Evaluation
All of the Client Script debugging strategies reviewed in the previous module also work for UI
Policies. In addition, UI Policies have the Debug UI Policies option. This is the only debugging
strategy for seeing the evaluation of a UI Policy's Condition.
• Lab 3.1
– Time: 20-25m
– Incident Resolved / Closed UI Policy
• You will write, test, and debug a UI Policy
Lab Summary
You will achieve the following:
• Write, test, and debug a UI Policy
• The UI policy should:
o Trigger when the State is set to Resolved.
o Change Urgency and Impact fields to read-only.
o Change the Resolved by field to mandatory.
o Display an Info Message.
• A Cloud Dimensions' Phase II requirement will be complete.
Business Problem
1. When closing Incident records, IT analysts are changing the value of the Impact and
Urgency fields in an effort to manipulate SLA results.
A. Create a UI Policy
1. Navigate to System UI > UI Policies.
a) Scroll down to the UI Policy Actions Related List and select the New button.
c) Select Submit.
d) Examine the record you just created in the list of UI Policy Actions. Notice the red
dot to the left of urgency? This indicates there is an error that requires attention.
Select the urgency link to open the record.
e) An error message appears indicating there are multiple UI Policies with the same
Order for this field. Select the Make fields read-only on close link in the error
message to open the conflicting UI Policy record.
f) If the Default view of the form opens, select the Advanced view Related Link to
display the Order field. Record the Order of the Make fields read-only on close UI
Policy here:
__________________________
g) Return to the Lab 3.1 Incident State Resolved UI Policy. If the Default view of the
form opens, select the Advanced view Related Link.
h) Change the Order field value to a value greater than the conflicting UI Policy
Order field's value.
j) Notice the red dot to the left of the urgency UI Policy Action is no longer visible.
7. Examine the following pseudo-code for the Execute if true script you will write:
• When the condition is true
o If the Closed code, Closed notes, or Resolved by fields do not have values
§ Display an Information Message reminding the analysts mandatory fields
are required before saving the record.
9. Select Update.
3. Did the Information Message appear at the top of the form? If not, debug and re-
test.
4. If the user updating a record selects one of these two states in error and
immediately sets the value of State back to In Progress, does the Info Message at
the top of the form disappear?
7. Select Update.
10. Once the Info Message appears at the top of the form, update the value of State to
In Progress? Does the Info Message at the top of the form disappear? If not, debug
and re-test.
11. Does the Reverse if false field need to be selected in order for the Execute if false
script to execute?
____________________
12. When a UI Policy condition is not met and the Reverse if false field is selected, does
the reverse of what is scripted in the Execute if true field occur?
_____________________________________________________________________
_____________________________________________________________________
4. Select the Clear log button ( ) to remove any messages in the JavaScript Log.
5. Force the UI Policy to execute again by setting the value of State to either Resolved
or Closed.
6. Locate the debugging information in the JavaScript Log for the Lab 3.1 Incident
Resolved/Closed UI Policy.
____________________
____________________
9. Select the Clear log button ( ) to remove any messages from the JavaScript Log.
11. Locate the debugging information in the JavaScript Log for the Lab 3.1 Incident
Resolved/Closed UI Policy.
12. Examine the debugging information for the evaluation of the condition. What did
the condition evaluate to?
____________________
13. Examine the debugging information for the UI Policy Actions. Were the correct fields
made read-only or mandatory?
____________________
15. Disable UI Policy Debugging by selecting System Diagnostics > Session Debug >
Disable UI Policies Debug on the Application Navigator.
Lab Completion
Great job! You successfully created a UI Policy that works everywhere in the platform.
Client UI Policy
Script
Execute on form load ✔ ✔
Execute on form save/submit/update ✔
Execute on form field value change ✔ ✔
Have access to a field's prior value ✔
Execute on list field value change(s) ✔
Execute after Client Scripts ✔
Require scripting ✔
Client-side scripts manage forms and their fields. Client Scripts and UI Policies both execute client-
side and use the same API. Use this table to determine which script type is best suited to your
application needs.
Discuss: Why, when, and how often would you use the capabilities shown in this module.
Department or
Group Catalog Populate Manager
Client Script and Name
manages the Catalog Client
display of certain Script auto-
fields on the form populates the
based on the Name and
v alue selected in Manager fields
this Multiple based on the
Choice field v alue selected in
the Group field
Catalog client scripts provide form validation and dynamic effects. This control of the form makes
the catalog reactive to a user’s inputs for an easy, curated, and rich user experience.
This is accomplished with Client Scripts that execute on the client-side (in your web browser).
Be aware that different browsers may present items in different ways. Always test your work in the
different browsers where possible (including mobile devices).
.
What exists baseline?
• 18 Catalog Client Scripts exist baseline
FAQ’s
When to execute
What to execute
Variables in a Catalog UI Policy condition must be visible (even if it is hidden by another UI policy or
read-only) on the form for the condition to be tested. Catalog UI Policies can also be applied when
the variables are present in a Requested Item or Catalog Task form.
Catalog UI Policies without a condition execute every time a form loads and/or is changed.
IMPORTANT
Not all Catalog UI Polices require scripting!
Applies to: Select the type of item this UI Policy applies to (A Catalog Item or A Variable Set).
Catalog item/Variable set: Select the catalog item or a variable set this UI Policy applies to.
Short description: Enter a brief description of the Catalog UI Policy. Use this field as a pseudo name.
Application: Identifies the scope of the Catalog UI Policy.
Active: Select the check box to enable the Catalog UI Policy. Clear the check box to disable it.
Order: Sequence in which policies are applied, from lowest to highest. Use when multiple policies
for the same table contain conflicting logic. Configure the form to display the existing field.
When to Apply
Catalog Conditions: Use the Condition builder to configure simple conditions for the policy using
Catalog Item variables. The policy is applied if the conditions evaluate to true.
Applies on a Catalog Item view: Select the check box to apply the policy to Catalog Items on the
order screen.
Applies on Catalog Tasks: Select the check box to apply the policy on a Catalog Task form.
Applies on Requested Items: Select the check box to apply the policy on a Requested Item form.
Applies on the Target Record: Select the check box to support the policy on a record created for
task-extended tables via Record Producers.
On load: Select the check box to apply the policy when the form loads, clear the check box to
apply the policy only when the form changes.
Reverse if false: Select check box to reverse the policy if the Catalog Conditions evaluate to false.
Script
Run scripts: Select the check box to script complex conditions and actions.
Run scripts in UI Type: Identify where policy executes (Desktop, Mobile/Service Portal, or All).
Execute if true: Script to execute when the Catalog Conditions evaluate to true. If Catalog
Conditions is left blank, script in this field always executes. Use to script complex conditions.
Execute if false: Script to execute when the Catalog Conditions evaluate to false.
Recall from ServiceNow Fundamentals training, a Variable Set allows you to define a set of variables
to be stored as a Variable Set for future use.
A Catalog UI Policy for Catalog Items always takes precedence over Catalog UI Policies for Variable
Sets.
Search for the Service catalog variable sets article on docs.servicenow.com for more information
on Variable Sets.
IMPORTANT
Applying Catalog UI Policy Actions on a Variable Set is NOT supported on Service Portal.
• Both Catalog Item variables and Variable Set variables are available to
Catalog Client Scripts and Catalog UI Policies
• Allows you to manage the behavior of any variable at the Catalog Item level
If a Variable Set behaves the same each time it is used, manage its behavior with a Catalog Client
Script or Catalog UI Policy at the Variable Set level.
If a Variable Set behaves differently each time it is used, manage its behavior with a Catalog Client
Script or Catalog UI Policy at the Catalog Item level.
• Use the Catalog Client Script and Catalog UI Policies Related Lists
• Identifies the related elements of the current Catalog Item
• Bottom of the Catalog Item form
You can also use the Application Navigator to locate the Catalog Client Script and Catalog UI Policies
modules. You can save the modules as favorites too!
• Lab 4.1
– Time: 15-20m
– Control Variable Choices Catalog Client Script
• Practice scripting using Catalog Client Scripts and Catalog UI
Policies
• Lab 4.2
– Time: 20-25m
– Control Out of State Shipping Catalog UI Policy
• Practice using a Catalog UI Policy to easily configure the display of
specific location fields
Lab Summary
You will achieve the following:
• Practice scripting using Catalog Client Scripts and Catalog UI Policies.
• You will first create a new Catalog Item for users to request new toner cartridges.
Users are able to order individual cartridges, as well as a multipack option with
different colors.
• Rather than create separate Catalog Items for the different options, you will create a
single Catalog Item to contain the various options, then use a script to filter the
options according to the role of the logged-in user.
o All users may only order black printer cartridges.
o Users with the ITIL Admin role may order all printer cartridges (black and color).
A. Preparation
1. Navigate to Self-Service > Knowledge.
3. Select the Toner.png article. The file automatically downloads to your computer.
4. Select Submit.
6. Compare your Which pack type would you like to order? Variable record with the
image below, make any adjustments if necessary.
Note: Consider configuring the Question Choices List Layout to include the Price and Order
columns. Select any Column header Context menu, then select Configure > List Layout.
8. Select Try It on the Brother Network-Ready Printer Toner Catalog Item's Header bar.
1. On the Brother Network-Ready Printer Toner Catalog Item form, configure the
related lists to include Catalog Client Scripts
2. Scroll down to the Catalog Client Scripts Related List and select New.
Note: Notice the Applies on a Catalog Item view field is pre-populated. This is because you
navigated to this form from a Catalog Item record.
7. Select Update.
1. On the Brother Network-Ready Printer Toner Catalog Item's Header bar, select Try It.
2. Confirm only black printer cartridges are available for selection. If not, debug and re-
test.
5. Use the Search catalog field to locate the Brother Network-Ready Printer Toner
Catalog Item. Select it when it appears in the drop-down list.
7. Confirm Bow can order both black and CYM printer cartridges. If not, debug and re-
test.
8. End the impersonation. You should be logged in as the System Administrator when
this step is complete.
Lab Completion
Excellent work! You have successfully controlled available items for order using a Catalog
Client Script.
Lab Summary
You will achieve the following:
• Use a Catalog UI Policy to easily configure the display of specific location fields.
• The Catalog Ui policy should allow:
o Regular users order a 'Brother Network-Ready Printer Cartridge', they are
only provided a list of California locations as delivery options.
o Users with 'itil_admin' role can choose location outside of California,
however they will receive a message reminding them additional charges
will be applied to the receiving location.
Lab Dependency: You must have Lab 4.1 Control Choices with a Catalog Client Script
complete, as this exercise continues to build on the Catalog Item created in the previous lab.
2. Locate and open the Brother Network-Ready Printer Toner Catalog Item.
Question
Question: Select a California location for delivery
Name: location_ca
3. Select Submit.
6. Select Submit.
7. Compare your Brother Network-Ready Printer Toner Variable records with the
image below; make any adjustments if necessary.
2. Add statements to the existing script to also restrict the display of the California
delivery? [ca_location] and Select a location outside of California for delivery
[location_other] fields to users with the 'itil_admin' role.
3. Select Update.
1. From the Brother Network-Ready Printer Toner Catalog Item form, configure the
related lists to include Catalog UI Policies.
5. Select Submit.
7. Compare your Catalog UI Policy Actions with the image below; make any
adjustments if necessary.
6. Select Update.
1. Select Try It on the Brother Network-Ready Printer Toner Catalog Item's Header bar.
2. Complete the Which pack type would you like to order? and Select a California location
for delivery fields. Were the fields displayed on the form? If not, debug and re-test.
4. Locate and open the Brother Network-Ready Printer Toner Catalog Item.
5. If these three fields do NOT display on the form, debug and re-test.
• Which pack type would you like to order?
• California delivery?
• Select a California location for delivery
6. Update the value in the California delivery? field to No. If the following three actions
do NOT occur, debug and re-test.
7. Update the value in the California delivery? field to Yes. If the following three actions
do not occur, debug and re-test.
8. End the impersonation. You should be logged in as the System Administrator when
this step is complete.
Lab Completion
Great job! You successfully implemented one single Catalog UI Policy to perform numerous
actions. It is always considered good practice to use a Catalog UI Policy vs. a Catalog Client
Script whenever possible.
Discuss: Why, when, and how often would you use the capabilities shown in this module.
GlideSystem
Labs
GlideRecord
5.1 Debugging Business Rules
Ev ents
5.2 Current and Previous
Script Includes 5.3 Display Business Rules and Dot-walking
UI Actions
Flow Designer
In this module you will write, test, and debug Business Rules.
Server-side Debugging
INC000002 5137153cc611227
c000bbd1bd8cd2
005
INC000000 681ccaf9c0a8016
3 400b98a06818d5
7c7
Business Rules respond to all record accesses regardless of access method: forms, lists, or Web
Services.
.
Server-side Debugging
Navigate to System Definition > Business Rules and select the New button to create a new Business
Rule.
Although not included by default, it is recommended you add the Description field to the Business
Rule form to document the Business Rule.
Insert – select this check box to execute the Business Rule when a record is inserted into the
database.
Update – select this check box to execute the Business Rule when an existing record is updated.
Filter Conditions – must return true for the Business Rule logic to execute.
Role conditions – select the roles that users who are modifying records in the table must have for
this Business Rule to execute.
When the Advanced check box is selected, additional configuration options are available on the
When to run tab:
When – timing of Business Rule script execution relative to the record access.
Order – order of execution; executed from low to high.
Delete – select this check box to execute the Business Rule when a record is deleted from the
database.
Query – select this check box to execute the Business Rule when a table is queried. Business Rules
defined for a database view can only run on Query. A Business Rule for a database view cannot run
on insert, update, or delete.
User or Before
Database
System Query
Query
Query Rules
Display Form
Rules Submit
When Query is part of the trigger condition, the Business Rule runs before the database query.
User or System Before Query Database Display Form Before Database After Async
Query Rules Query Rules Submit Rules Update Rules Rules
Before Query
Business Rule number caller_id
5137153cc611227
queries the INC000002
c000bbd1bd8cd2
005
database INC0000003 681ccaf9c0a8016
400b98a06818d57
c7
Before Query Business Rules execute synchronously. The current Business Rule must finish execution
before the next Business Rule runs.
When a user is not authorized to see all records in a list, the "Number of rows removed by Security
constraints" message appears. Before Query Business Rules such as the baseline 'incident query'
Business Rule act like Access Control Lists (ACLs) and prevents users from seeing certain records.
When access is controlled through a Before Query Business Rule, the "Number of rows removed by
security constraints" message is not displayed and the user does not know access is restricted.
User or System Before Query Database Display Form Before Database After Async
Query Rules Query Rules Submit Rules Update Rules Rules
• Execute after the data is read from the database and before the form is
presented to the user
• Primary purpose is to populate the g_scratchpad global object
• Example: Provide Client Scripts with access to data from other records
Display
number caller_id
INC000002 5137153cc61
Business Rule executes
1227c000bbd
1bd8cd2005
and populates the
INC00000
03
681ccaf9c0a
8016400b98a
g_scratchpad object
06818d57c7
Display Business Rules execute when a user requests a record form. Data is read from the database,
the Display rules are executed, and the form is presented to the user.
The g_scratchpad global object has no property/value pairs unless populated by a Display Business
Rule. For example, the sys_created_by and sys_created_on fields are not part of the Incident form.
To access their values from a Client Script would require a call to the server. Server calls are
expensive from a processing time perspective and should be avoided. Instead, the Display Business
Rule populates the g_scratchpad object when the form loads and the Client Script reads the values
from the g_scratchpad object.
Client Script
if(g_scratchpad.createdBy == 'admin'){
g_form.setValue('opened_by',g_scratchpad.caller,
g_scratchpad.callerDV);
}
User or System Before Query Database Display Form Before Database After Async
Query Rules Query Rules Submit Rules Update Rules Rules
• Execute after form submission and before record is updated in the database
• Example: Populate 'closed_by' with the name of the currently logged in user
Before Business Rules execute synchronously. The current Business Rule must finish execution
before the next Business Rule runs.
User or System Before Query Database Display Form Before Database After Async
Query Rules Query Rules Submit Rules Update Rules Rules
• Execute after form submission and after the record update in the database
• Example: Cascade changes made to the approval field of a Service Catalog
request to the requested items attached to that request
number caller_id
After
INC000002 5137153cc61 Business
1227c000bbd
1bd8cd2005 Rule
INC00000 681ccaf9c0a
03 8016400b98a Executes
06818d57c7
After Business Rules execute synchronously. The current Business Rule must finish execution before
the next Business Rule runs.
User or System Before Query Database Display Form Before Database After Async
Query Rules Query Rules Submit Rules Update Rules Rules
Scheduler
number caller_id
INC000002 5137153cc61
schedules
1227c000bbd
1bd8cd2005
Async Business
INC00000
03
681ccaf9c0a
8016400b98a
Rule execution
06818d57c7
Async Business Rules are queued by the scheduler to run as soon as they can be fit in, this allows
the current transaction to finish without waiting for the rule. They do not have access to the
previous version of a record.
The Priority field is visible on the Business Rule form when Async is selected in the When field. The
value in this field is used when creating the associated scheduled job. By convention, the Priority
numbers in an Async Business Rules contain three digits. For example: 100, 300, or 675.
To see Async Business Rules queued up for execution, open System Scheduler > Scheduled Jobs >
Scheduled Jobs. Async Business Rules appear with their names prepended with ASYNC. They go in
and out very quickly so they can be hard to catch.
Server-side Debugging
Set field values – set values for fields in the selected table using the choice lists.
Add message – select this checkbox to identify if a message will be displayed to the user on the next
rendered screen when the Business Rule executes.
Message – compose the message to be sent.
Abort action – select this check box to abort the current database transaction. If you select this
option, you cannot perform additional actions on the record. You can still display a message to users
by selecting the Add message checkbox and composing the message.
Use the scripting fields on the Advanced tab when the Business Rule’s conditions and actions are
more complex. Example: evaluating the previous value of a field.
Condition – create a JavaScript statement to specify when the Business Rule should execute. The
Condition field returns true when left blank.
Script – JavaScript that executes server-side when the When to run criteria is met and the
Condition field returns true. Insert the appropriate script logic to be processed when the Business
Rule executes.
IMPORTANT
Condition(s) on the When to run tab and condition(s) in the Condition field on the
Advanced tab must both evaluate to true for the logic in the Script field to execute.
Server-side Debugging
current is an object that stores the current record’s fields and values; new/modified values. A script
can change a field's value many times current will store the most recent value. For example:
if(previous.priority == current.priority {
return;
}
previous is an object that stores the record’s fields and values before any changes were made; the
original values when the form loaded. Reference this object using previous.<field_name>. For
example:
if(previous.priority == 1){
//logic here
}
IMPORTANT
The previous object is not available in a Async Business Rules.
current.caller_id.department.name Example
Client-side you must use the getReference() method to access data from related record. Recall this
method requires a call to the server from the client and it only allows one-level of dot-walking on
the retrieved object. Business Rules run on the server and have direct access to the database. To
hop from table to table you use a strategy called 'dot-walking'.
Dot-walking is for a one-to-one relationships and not for one-to-many (e.g. – related lists).
In this example, the current object is an Incident [incident] table record. The statement
current.caller_id.department.name jumps from the Incident [incident] table record to the related
record in the User [sys_user] table where the sys_id matches the caller_id from the Incident table.
The department id is then used to jump to the matching record on the Department
[cmn_department] table. The caller's department name is then retrieved.
Expand the Fields category to see the list of variables in the current object.
Server-side Debugging
Use the System Logs > System Log modules to view messages logged by the gs.log(), gs.error(),
gs.info(), gs.warn(), and gs.debug() methods. gs.log() will always write a message, so overuse of this
can adversely affect performance. Whenever possible, comment out or remove gs.log().
IMPORTANT
Keep in mind, If you are developing in a scoped application, you will not be able to use
gs.log(). Error, warn, info, and debug logging methods are intended for Scoped
Applications, but can be used in the Global Scope. These logging methods provide
verbosity levels to a log message.
To locate a specific Business Rule in the Debug Output look for the string ==> '<Business Rule
Name>' (Ctrl-F/Cmd-F). All debugging information following that string until the string <==
'<Business Rule Name>' pertains to the Business Rule.
Select System Security > Debugging > Stop Debugging to stop writing debugging output to forms.
IMPORTANT
Remember to disable the debugger when you are done testing, because debugger
consumes resource when it is enabled.
When detailed debugging is enabled, record field values set in Business Rules appear in the
debugging output. The syntax is:
<field name>: <old value> => <new value>
This strategy allows you to see changed values for all fields changed by Business Rules.
Select System Security > Debugging > Stop Debugging to stop writing debugging output to forms,
as the Debugger can cause performance issues in a Production instance.
The Script Debugger can also be launch in the Studio by selecting File > Script Debugger.
The Script Debugger is session specific; no other users are impacted. Each user can only have one
Script Debugger console open and executing at a time.
Administrators can use the Script Debugger while impersonating another user, but only if the
impersonated user has the admin or script_debugger role and has read access to the target script.
The Script Debugger only debugs server-side synchronous scripts. It is not possible to step through
scripts running asynchronously as they are not running in the the same session as the logged-in user.
A debugger transaction remains open as long as the user session is valid. If the user logs out, or the
session times out (which will occur if paused for too long), the system stops the debugger
transaction. If this occurs, it can be re-enabled by selecting the on button, pressing F2, or by closing
and re-opening the debugger.
Current line
highlighted
when paused
• Every breakpoint the logged-in user has defined (across multiple scopes)
appears in the list
Breakpoints are an intentional stopping or pausing place in a script, for debugging purposes.
The Script Debugger lists all of the logged-in user’s Breakpoints across the platform (regardless of
scope). The artifacts are listed by script type, script name, and line number. The Script Debugger
updates this list as you add and remove breakpoints in real time.
In the coding pane, current breakpoint is highlighted in red and inactive breakpoints are highlighted
in blue.
See ServiceNow's Product Documentation for the full list of Available Transaction Details and their
descriptions.
The Coding Pane Header displays the script type and name of the script currently in the coding
pane.
Start Debugging (F2) – enables the Script Debugger for the current user. If the Script Debugger is
already enabled, the Pause Debugging icon will display instead.
Pause Debugging (F2) – stops current debugging session, and disables the Script Debugger for the
current user. The Script Debugger does not pause on breakpoints for the current user until it is
restarted. If the Script Debugger is already paused, the Start Debugging icon will display instead.
Resume Script Execution (F9) – advances from the current breakpoint to the next breakpoint. If no
breakpoints exist, the script runs to completion.
Step Over Next Function Call (F8) – advances to the next evaluated line of script based on current
conditions. The Script Debugger skips any lines of code that do not run because their conditions are
not met. For example, when the condition of an if() statement is not true, the Script Debugger skips
the code block for the condition.
Step Into Next Function Call (F7) – when the Script Debugger pauses ON a method call, this control
allows the user to advance to the first line of executed code in the called method. Stepping into a
method also updates the current position within the Call Stack. If the user does not have read
access to the method call, this control instead behaves like Step Over.
Step Out of Current Function (Shift + F8) – when the Script Debugger pauses WITHIN a method call,
this control allows the user to exit the called method and return to the calling script from the Call
Stack. If the user is not within a method call, this control instead behaves like Step Over.
Variable information is only visible when the Script Debugger pauses on a Breakpoint.
Local – displays a list of local scope variable names and their values. Includes both the variables you
declared inside the script, as well as declared baseline.
Closures – displays a list of global scope variable names and their values set by function closure.
Global – displays a list of global scope variable names and their values.
EXECUTION_PAUSED – displays when the Script Debugger pauses on a breakpoint, or when the user
steps over, steps into, or steps out to the next line of code.
WAITING_FOR_BREAKPOINT – displays when the Script Debugger is searching for the next
breakpoint. Users rarely see this status as it changes quickly back to EXECUTION_PAUSED as soon as
the next breakpoint pauses the script.
WAITING_FOR_FIRST_BREAKPOINT – displays when the user first opens the Script Debugger and it
is ready to pause the script and display debugging information.
OFF – displays when the Script Debugger is inactive and does not pause scripts or display debugging
information. The Script Debugger turns off when a user pauses or closes the Script Debugger, the
user session times-out or ends for any reason, or the Administrator resets all Script Debugger
instances by navigating to the debugger_reset.do page.
By default, the platform supports debugging [(# of semaphores on the instance) /4] concurrent
transactions. For example, if you have 12 semaphores by default 3 transactions can be debugged at
a given point in time.
Administrators can specify the number of concurrent transactions the system can debug by setting
the glide.debugger.config.max_node_concurrency system property. The system can debug up to [(#
of semaphores on the instance) - 2] concurrent transactions.
To see the platform’s Script Debugging semaphore set, type stats.do in the Application Navigator
followed by <enter> on the keyboard. Example:
Semaphore Sets
Debug
Available semaphores: 4
Queue depth: 0
Max queue depth: 0
Maximum transaction concurrency: 4
Maximum concurrency achieved: 0
Lab Summary
You will achieve the following:
• Debug Business Rules using several different strategies.
Note: Should the Script Debugger lose connection to the script you are debugging at any time,
simply close and re-open the window.
A. Preparation
1. Navigate to System Definition > Business Rules.
2. Locate and open the Lab 5.1 Business Rule Debugging Business Rule.
4. On the Advanced Tab, overwrite the string <your_initials> with your personal
initials in the Script. Example:
6. Review the Business Rule and read the script so you understand:
• when it triggers
• what it executes
7. Consider saving this Business Rule as a Favorite as you will be opening the record
often throughout the lab. Select Create Favorite on the form’s Context menu.
2. Select the Open Script Debugger ( ) icon on the Syntax Editor toolbar or the
System Diagnostics > Script Debugger module on the Application Navigator. The
Script Debugger opens in another browser window.
3. Notice the list of all breakpoints set in the platform by you appears on the left-side
of the code pane.
4. Set another breakpoint by clicking the gutter to the left of the line beginning with
SlaTargetNotification.
5. What can you conclude about where breakpoints can be set? Record your answer
here:
_____________________________________________________________________
a) Open any active Incident, change the value of State to anything except Closed.
Note: Had the Script Debugger window not been open, the script would have executed normally
without stopping at any breakpoints.
8. Script execution is paused at the first breakpoint. How can you tell? Explain your
reasoning:
____________________________________________________________________
9. Examine the value of the myNum variable in the Local variables section on the right-
side of the window. Does it contain the value you expected? __________________
10. Select the Next Breakpoint button ( ) to resume script execution and pause at the
next breakpoint.
11. Re-examine the value of the myNum variable in the Local variables section. What
value does it contain now? __________________
_____________________________________________________________________
_____________________________________________________________________
13. Repeat steps 9-11 to watch the values of the priorityValue and createdValue
variables update as you step through the code.
Note: Specifically notice the value of createdValue, this type of output is extremely valuable
when you are scripting dates. E.g. you may write a script similar to:
and it does not work. This output will quickly confirm the syntax/value in the [sys_created_on]
field and you can then adjust the value of ‘somevalue’ accordingly.
14. When you reach the breakpoint on the line beginning with SlaTargetNotification,
select the Next Breakpoint button one last time to complete the execution of the
script.
15. Think of an example in the past where you declared variables in a script and they did
not return the values you were expecting. Would it have been helpful to have
variable value output available like this?
_____________________________________________________________________
2. Force the Lab 5.1 Business Rule Debugging Business Rule to execute:
_______________________________________________________________
________________________________________________________________
___________________________________________________________________
___________________________________________________________________
7. Select the Next Breakpoint button as many times as needed to complete the
execution of the script.
Note: You will learn about Script Includes in an upcoming module, for now you are only adding
a breakpoint to the script.
3. Set a breakpoint in this script by clicking in the gutter to the left of the line beginning
with gs.log.
4. Select the Open Script Debugger button on the Syntax Editor toolbar. The Script
Debugger opens in another window.
5. Notice the list of breakpoints now includes the one you just set in step-3.
6. Select any one of the Lab 5.1 Business Rule Debugging lines to load that script in the
code pane.
7. Update the breakpoints so only the line of code beginning with var createdValue
and try are set.
a) Open any active Incident, change the State value to anything except Closed.
10. You are stopped at the first breakpoint in the Lab 5.1 Business Rule Debugging
script. Review the information displayed in the Call Stack and Transaction Detail on
the left-side of the screen.
11. How can you be sure which script you are currently debugging? What does the Code
Pane Header read? Record your answer here:
_____________________________________________________________________
12. Notice the very next line in the script after the breakpoint you are currently paused
at calls the SlaTargetNotification Script Include. Select the Next Breakpoint button
one time.
13. Notice the information in the Call Stack now includes the Script Includes breakpoint details.
14. How can you be sure which script you are currently debugging? What does the Code
Pane Header read? Record your answer here:
_____________________________________________________________________
16. Notice the information in the Call Stack on the left-side of the screen changed.
17. What does the Code Pane Header read? Record your answer here:
_____________________________________________________________________
18. Select the Next Breakpoint button one last time to complete the execution of the
script.
2. Select the breakpoints to remove them. (There should be no breakpoints set in the
script after this step is complete.)
• thisFunctionDoesNotExist() is in a try/catch.
• thisFunctionAlsoDoesNotExist() is NOT in a try/catch.
Predict what will occur when the Business Rule executes. Record your answer here:
_____________________________________________________________________
4. Force the Lab 5.1 Business Rule Debugging Business Rule to execute:
a) Open any active Incident, change the State value to anything except Closed.
b) Select Update.
5. Open System Logs > System Log > Script Log Statements. Which undefined function
produced an error and why?
_____________________________________________________________________
_____________________________________________________________________
Note: If you are debugging using the Script Debugger, note that undefined functions not
wrapped in a try/catch stop script execution and the remaining breakpoints are ignored. If this
happens to you, check this list instead to get more information about why a function call may
have failed.
2. Recall the condition for the execution of Lab 5.1 Business Rule Debugging Business
Rule is current.state !=7. Update a record that will not trigger the Business Rule.
3. Scroll to the bottom of the Incident form and search for the execution of the Lab 5.1
Business Rule Debugging Business Rule by searching for the string ==> Lab 5.1
Business Rule Debugging. Did your test meet the Business Rule's Condition criteria?
How can you tell?:
_____________________________________________________________________
4. Test the case where the Condition field returns false. Examine the debugging output
at the bottom of the Incident form for this lab.
5. Disable Business Rule Debugging: System Security > Debugging > Stop Debugging.
6. Make the Lab 5.1 Business Rules Debugging Business Rule inactive.
Lab Completion
Well done! You have successfully practiced testing scripts using five different server-side
debugging techniques.
Lab Summary
You will achieve the following:
• Use the current and previous global objects in a Business Rule.
• Create two new form fields for use in your Business Rule.
• Practice debugging.
• A Cloud Dimensions' Phase II requirement will be marked complete.
Business Problem
The current process to gather Root Cause Analysis (RCA) at Cloud Dimensions asks users to
provide their findings and documentation in the 'Additional comments' field prefixed by the
text "RCA: ". This strategy has proven to be unsuccessful as the prefix is often forgotten, and it
is difficult to extract the data from records with multiple RCA updates. RCA reporting is
currently performed manually, it takes hours to produce, and the results are often incomplete.
Project Requirement
Create a new 'RCA' field on the Incident form to capture root cause analysis documentation.
For reporting purposes, create a second field on the Incident form called 'RCA included' to
easily identify records where root cause analysis documentation is included. In the event the
updating analyst forgets to update this field, the system should evaluate the 'RCA' field and if
populated, the 'RCA included' field should also be selected (checked). In the case where an
existing value in the 'RCA' field is removed, the check should be removed from the 'RCA
included' field as well.
a) Open an Incident.
b) Right-click the form's Context menu and select Configure > Form Design.
c) Select the Field Types tab on the left side of the screen.
e) Select the Edit this field (gear) icon on the right side of the field.
h) Drag a String field to the form below the RCA included field.
Label: RCA
Name: u_rca
Max length: 1000
j) Select Save.
2. On the Advanced tab, within the executeRule() function in the Script field, type
try followed by the <tab> key to insert the try Syntax Editor Macro (created in Lab
2.1).
3. Select the Format Code icon on the Syntax Editor toolbar to properly align the script.
4. Update the statement in the catch block to use the server-side gs.log() method
instead of the client-side g_form.addErrorMessage() method.
7. Select Submit.
8. Does the RCA included field need to remain visible on the form? _______________
Lab Completion
You have successfully completed the lab and practiced using the current and previous global
objects.
Lab Summary
You will achieve the following:
• Write a script using g_scratchpad global object, Display Business Rules, and dot-
walking.
4. Select Submit.
4. Select Submit.
2. If the Resolved by field has no value, enter the user of your choice and Save the Incident.
4. Did the confirmation dialog box appear? Did the g_scratchpad properties resolve
correctly? If not, debug and re-test.
6. What happened to the State field? Is this the expected behavior? If not, debug and re-test.
13. Did the reopen count increase by 1 correctly? If not, debug and re-test.
Lab Completion
You have successfully completed the lab and practiced using the g_scratchpad global object,
Display Business Rules, and dot-walking. You are ready to take it up a notch!
• Write condition statements in the Condition field and not in the script so
unnecessary scripts do not run
• Choose an appropriate debugging strategy for your situation
• Add the Description field to the Business Rule form to document for yourself and
others what the rule does
• Comment your scripts!!
Discuss: Why, when, and how often would you use the capabilities shown in this module.
Business Rules
Labs
GlideSystem Lab 6.1 Setting the CAB Date
GlideRecord Lab 6.2 Re-open Problem Date Validation
Ev ents
• Collection of methods
Logged in user is Beth Anglin
• Execute server-side Today is 7 September 2017
Write debugging information
• Access system-level information
– Logged in user
– System
– Date and time
GlideSystem methods all begin with gs. For example, the method gs.addInfoMessage() displays
informational messages to the user at the top of a form or list.
The complete set of GlideSystem methods can be found on the ServiceNow Developer site.
getUser() – returns a reference to the User object for the current user.
getUserDisplayName() – returns the name field of the current user (Fred Luddy instead of
fred.luddy).
getUserID() – returns the sys_id of the current user.
getUserName() – returns the username of the current user (fred.luddy).
hasRole() – returns true if the user has the specified role.
hasRoleInGroup() – returns true if the user has the specified role within a specified group.
This example shows the different values returned by the getUserXXXX() methods.
beginningOfLastWeek() – date and time for the beginning of last week in GMT (yyyy-mm-dd
hh:mm:ss).
beginningOfNextMonth() – date and time for the beginning of next month in GMT.
dateDiff() – calculates the difference between two dates.
endOfLastWeek() – date and time for the end of last week in GMT.
endOfNextMonth() – date and time for the end of next month in GMT.
minutesAgo()/daysAgo()/quartersAgo()/monthsAgo()/yearsAgo() – returns the date and time a
specified number of minutes/quarters/months/years ago. Negative numbers will show a date and
time in the future.
now() – current date.
nowDateTime() – current date and time in the user-defined format.
This example was prepared using GlideSystem methods in a Business Rule on the User [sys_user]
table.
When passed a date field as an argument, the getDisplayValue() method returns the date and time
in the user's time zone rather than in GMT.
Output:
2015-01-01
2015-01-01 00:00:00
The GlideDateTime class provides methods for performing operations on GlideDateTime objects,
such as instantiating GlideDateTime objects or working with glide_date_time fields.
Note: Methods can use the Java Virtual Machine time zone, so use equivalent local time and UTC
methods whenever possible to prevent unexpected result.
The complete set of GlideSystem methods can be found on the ServiceNow Developer site.
1. Select API.
2. Select Server.
3. Select LEGACY.
4. Locate and expand the GlideSystem category on the left.
• Lab 6.1
– Time: 10-15m
– Setting the CAB Date
• Write a Business Rule using GlideSystem date and time methods
• Lab 6.2
– Time: 10-15m
– Re-open Problem Date Validation
• Write a Business Rule using GlideSystem date and time methods
Lab Summary
You will achieve the following:
• Write a Business Rule using GlideSystem date and time methods to set the CAB date
for a Change Request to Wednesday of next week.
• Mark a Cloud Dimensions' Phase II requirement complete.
Business Problem
2nd level IT Analysts from various teams have requested the Change Management team use
the CAB date field on the Schedule tab to inform them at which CAB meeting their Change
Request will be reviewed. The Change Management team has been doing their best to
populate the field manually, but many times the information is missed.
As CAB meetings are held every Wednesday, the Change Management team has requested the
field be automatically populated with next Wednesday's date. Using this strategy, they will
only be required to update the field if there is an exception vs. populating the date for every
new Change Request.
Project Requirement
Set the CAB date to Wednesday of next week for new Change Requests.
2. On the Advanced tab, within the executeRule() function in the Script field, type
try followed by the <tab> key to insert the try Syntax Editor Macro (created in Lab
2.1).
3. Select the Format Code icon on the Syntax Editor toolbar to properly align the code.
4. Update the statement in the catch block to use the server-side gs.log() method
instead of the client-side g_form.addErrorMessage() method.
2. Select Normal: Changes without predefined plans that require approval and CAB
authorization.
Hint: A common mistake is to forget to multiply by 1000. Make sure to account for the
milliseconds to get the correct date.
Lab Completion
Great job! You successfully completed the requirement and practiced using many different
GlideSystem methods in a server-side script.
Lab Summary
You will achieve the following:
• Write a Business Rule using GlideSystem date and time methods to verify if a
Problem hasn't been closed for more than 30 days if a user attempts to re-open the
record.
• Complete a Cloud Dimensions' Phase II requirement.
Business Problem
After analyzing the data, the Problem Management team determined it is common practice for
IT Analysts to re-open Problem records to document ongoing work performed on the same
Configuration Item (CI). In some cases, the re-open was valid. In other cases, the re-open was
not valid, as it was a new issue altogether.
After digging a little deeper, the team also determined where there was a valid re-open, the
failure of the permanent fix presented itself in less than one week.
To eliminate the practice of incorrectly re-opening Problem records, the Problem Management
team has put a policy in place stating Problem records cannot be re-opened after 30 days. The
team feels this window is sufficient to catch any valid re-opens. They are requesting
ServiceNow be configured to help enforce this policy.
Project Requirement
Prevent Problem records from re-opening if closed for more than 30 days.
8. Select Update.
3. Ensure the value in the Completed field (on the Other Information tab) is greater
than 30 days.
6. Do you see an error message at the top of the form? If not, debug and re-test.
9. Select OK and a message will appear to state the ui action has been updated to the
previous version.
10. Navigate to the UI Action Re-Analyze to confirm it has been restored to original
version.
Lab Completion
Well done! You successfully completed the requirement and practiced comparing dates in the
Global space using GlideSystem methods.
• You must use Scoped APIs when developing scripts for scoped applications
• The Scoped GlideSystem API provides methods for accessing system-level
information in scoped applications
– Logged in user
– General system
– Logging
• Error messages advise developers when methods are used in the wrong
scope
Scoped Glide APIs do not provide all the methods included in the global Glide APIs, and you cannot
call a global Glide API in a scoped application. The complete set Scoped GlideSystem methods can
be found on the ServiceNow Developer site.
1. Select API.
2. Select Server.
3. Select SCOPED.
4. Locate and expand the GlideSystem category on the left.
IMPORTANT
The Scoped GlideSystem API does not provide methods to work with date/time fields. Use
GlideDate or GlideDateTime methods (Scoped and Legacy). Detailed information on both
of these APIs can be found on the ServiceNow Developer site.
Scoped GlideSystem logging methods are available for scripts in private application scopes.
• debug() – sets the log Level to 'Debug'. Use to log informational messages useful for debugging.
• error() – sets the log Level to 'Error'. Use to log messages that might still allow the system to
continue running.
• info() – sets the log Level to 'Information'. Use to log informational messages describing progress.
• warn() – sets the log Level to 'Warning'. Use to log potentially harmful messages.
• isDebugging() – determines if debugging is active for a specific scope.
Navigate to System Logs > System Log > All to locate gs.error(), gs.warn(), and gs.info() output.
These messages along with messages from gs.debug() are also located at the bottom of a form
when System Debugging is turned on.
Spelling Error
If using logging methods in production, always select the appropriate log type for the event or log
message (error, info, warn or debug).
Discuss: Why, when, and how often would you use the capabilities shown in this module.
number sys_id
PRB000002 5137153cc611227
Record1 c000bbd1bd8cd2
Record2 005
PRB0000003 681ccaf9c0a8016
RecordN 400b98a06818d57
c7
GlideRecord queries can be called client-side but this should be avoided due to performance impact.
The getReference() method previously discussed in Module 3 – Client Scripts performs a GlideRecord
query.
number sys_id
This strategy outlines the necessary steps for creating and populating a GlideRecord object, then
processing any returned records.
The example creates a variable called myObj which is a GlideRecord object for the Change Request
[change_request] table.
The example shown only builds the select statement; it does not execute it.
• Must be in quotes
myObj.addQuery('priority','!=',1);
myObj.addQuery('work_notes','CONTAINS','Fixed');
Is the same as
myObj.addQuery('category','=','Hardware');
The _query() method provides the same functionality as the query() method. It is intended to be
used on tables where there is a column named 'query', which would interfere with using the query()
method.
• hasNext() steps through returned records and determines if there are any
more records
if(myObj.hasNext()){
//script logic
}
.hasNext() returns true when there is a next record, but does not load that record into the object for
processing. Select this method to execute script logic when a next record simply exists, but access to
the record's data is not needed.
By default queries with invalid field names run but ignore the invalid condition. A true/false
glide.invalid_query.returns_no_rows System Property can be added to the System Property table
with its value set to true to instead have invalid queries return no rows in the GlideRecord object.
The method _next() has the same functionality as next(). It is intended to be used on tables where
there is a column named 'next', which would interfere with using the next() method.
• Use the update() method to save changes to the records in the GlideRecord
• If record does not exist, it is inserted
while (incGR.next()) {
incGR.work_notes = "Related Problem " + current.number + "
closed with the following Close Notes:\n\n" +
current.close_notes;
incGR.update();
}
In the example shown, the work_notes fields in the returned Incident records are updated with the
the value currently in the related Problem's close_notes field.
To automatically insert GlideRecord syntax containing an addQuery() method, use the Syntax Editor
Macro vargr. This macro inserts an if() at end of the code stub, in most cases you will want to
change this to a while() so you can execute the script logic on all returned rows and not just the first
one.
To insert GlideRecord syntax containing an addOrCondition() method, use the script macro vargror.
Use an object variable and addQuery() to add the first condition and addOrCondition() for the
second condition.
select * from incident where (state < 3 OR state > 5) AND (priority = 1 OR priority = 5);
Each 'group' in the select statement is its own object in the script.
if(!current.parent_incident.nil()) {
var myObj = new GlideRecord('incident');
myObj.get(current.parent_incident);
myObj.u_rca = true;
myObj.update();
Unique value
}
Defines a GlideRecord based on the specified expression of name = value. If value is not specified,
then the expression used is sys_id = name.
Both of these options return the number of rows meeting the query criteria.
The first option, getRowCount(), is a lot less code to write but has a significantly larger performance
impact and is not recommended for use with tables with large amounts of data. This strategy
retrieves the rows one by one and increments a counter.
The second method, GlideAggregate() is more work for the developer, but results in a faster
execution. This strategy executes a true COUNT select statement: select COUNT(*) from
table_name; This strategy is always recommended for cases where the returned number of rows is
greater than 100 and for tables that grow continuously. If in doubt, use this strategy.
See the ServiceNow Developer site for more information on the GlideAggregate API.
Although this example looks overwhelmingly complex, it is easy to build the where clause(s) using
the Condition builder.
Remember, you can type <table name>.list into the Application Navigator’s Search field to quickly
open the list view for a table (e.g. entering sys_user.list will open the list view of the User [sys_user]
table in the content pane).
When right-clicking the breadcrumbs and selecting Copy query, the query copied to the clipboard
will contain only those parts of the query from where you clicked and to the left. In this example, if
you right-click on Approval=Approved, you will only have that part of the where clause. If you right-
click on Planned end date on This year, you will copy the entire set of where clauses.
IMPORTANT
Always test queries on a development instance prior to deploying them to a production
instance. An incorrectly constructed encoded query (e.g. including an invalid field name),
produces an invalid query. When the invalid query executes, the invalid part of the query
condition is dropped, and the results are based on the valid part of the query, which may
return all records from the table. Using an insert(), update(), deleteRecord(),
or deleteMultiple() method on bad query results can result in data loss.
For example, the baseline SNC - ITIL - Close Related Business Rule closes all related Incident records
when a Problem record closes. The Business Rule identifies the Problem table in its trigger, and the
GlideRecord query updates the appropriate Incident records.
The complete set of GlideRecord methods can be found on the ServiceNow Developer site.
1. Select API.
2. Select Server.
3. Select LEGACY.
4. Locate and expand the GlideRecord category on the left.
GlideRecord can handle a variety of data manipulation tasks, but can it restrict data to certain users?
Yes, the GlideSystem methods discussed in Module-6, like hasRole(), canRead(), and canWrite() used
in conjunction with GlideRecord will restrict data to users that have the correct roles. However, you
must include the appropriate conditional checks every time data is queried. This strategy is NOT
considered best practice.
• Lab 7.1
– Time: 20-25m
– Two GlideRecord Queries
• Practice using Business Rules to locate records from one table
and update another table
• Lab 7.2
– Time: 20-25m
– RCA Attached: Problem and Child Incidents
• Create a Business Rules to update records and related records
• Lab 7.3
– Time: 5-10m
– addEncodedQuery()
• Practice creating an Encoded Query and using
addEncodedQuery() in a GlideRecord
Lab Summary
You will achieve the following:
• Write a GlideRecord query to locate a set of Incidents
• Write a second GlideRecord that:
o query to locate a set of users.
o Trigger the Business Rule from one table, but make updates to records on a
different table.
3. Within the executeRule() function in the Script field, type vargr followed by the
<tab> key to insert the standard GlideRecord syntax (stored in the baseline Syntax
Editor Macro).
4. Select the Format Code icon on the Syntax Editor toolbar to properly format the
script.
c) Optional: Insert a blank line between the query() statement and the while()
statement for easy readability.
d) Compare your script with this code. Make any adjustments if necessary.
6. Update the GlideRecord query to find all active Incidents where Short Description
contains SAP.
8. Select Submit.
2. Use the Condition Builder to build the same query you just scripted.
3. Run the query and record the number of returned rows here: ________________.
4. Create a new Incident and populate the mandatory fields with values of your choice.
6. Did your script locate the expected records? If not, debug and re-test your Business
Rule.
Hint: VIP is a Boolean field on the User [sys_user] table. The VIP field is not displayed on the
User records unless the form/list is configured.
Hint: Use the GlideRecord update() method to modify the User records.
Note: Experienced scripters are encouraged to do this without looking at provided code,
however, if you are new to scripting and require assistance, you will find an example of a
Business Rule that can be used as a guide on the next page.)
2. Did your script locate and update the expected records? If not, debug and re-test
your Business Rule.
Lab Completion
Great job! You thoroughly understand how to query the database using GlideRecord
methods. If you were able to complete the second Business Rule on your own, bonus points
for you.
Script:
a) Use the Condition Builder on the Users [sys_user] table to build the same query
you just scripted. Make a mental note of the number of returned rows.
d) Navigate to System Logs > Script Log Statements to review the log message.
e) Did your script locate the expected records? If not, debug and re-test your
Business Rule.
Lab Summary
You will achieve the following:
• Create a Business Rule to update related Problem and Child Incident records. When
this lab is complete, you will mark a Cloud Dimensions' Phase II requirement
complete.
Business Problem
The Problem Management team currently updates Problems and Child Incidents manually with
the Root Cause Analysis (RCA) details from Parent Incident records. The team is requesting
automation be put in place to relieve them of the tedious and time-consuming updates.
Project Requirement
Create a Business Rule to update Problem and Child Incident records with RCA details from the
Parent Incident. To ensure the RCA details are finalized, ensure the Business Rule only
executes when the State of the Parent Incident changes to Closed.
4. Select Submit.
d) Select Submit.
2. Create another new Incident.
b) Select Submit.
b) Select Submit.
5. Navigate to the Child Incidents Related List and confirm both of your Child Incidents
appear in the list. If not, review your Child Incident records and ensure the Parent
Incident is identified in both of the records.
7. Select Update.
8. Open the Problem you recorded in step 1b. Do you see the Root Cause Analysis data
in the Activity list? If not, debug and re-test.
9. Open each of the Child Incident records. Are the RCA fields populated? If not, debug
and re-test.
Lab Completion
Well done! You have successfully updated records on two different tables using one Business
Rule.
Lab Summary
You will achieve the following:
• Re-write and augment a previous lab's GlideRecord query using the
addEncodedQuery() method.
Lab Dependency: You must have the Lab 7.1 VIP Users Business complete to do this lab.
A. Preparation
1. Open the VIP Business Rule you wrote in Lab 7.1 (users with Vice, VP, or Chief in
their title).
6. Use the Condition Builder to build a query looking for users with Vice, VP, or Chief in
their title.
7. Add an additional query to search for users who have the itil role.
c) Paste the copied query from your clipboard into the addEncodedQuery() method
as the parameter.
2. Select Update.
2. Was the expected number of records returned? If not debug and re-test your
Business Rule.
Lab Completion
Good job! You have successfully used the addEncodedQuery() GlideRecord method.
Follow these steps to locate Scoped GlideRecord information ServiceNow Developer site.
1. Select API.
2. Select Server.
3. Select SCOPED.
4. Locate and expand the GlideRecord category on the left.
production instances
• Perform all record queries in server-side scripts for improved performance
• Use _next() and _query() for tables containing next and query columns
• When deleting/inserting/updating records with GlideRecord methods,
practice writing the list of records to a log to insure you do not accidentally
modify records you still need before enabling the methods that modify the
database (there is no undo!)
The query() method executes a select statement •When would you use these
against a database table
capabilities?
Use a while loop to iterate over returned
GlideRecords
GlideAggregate() and getRowCount() tell how •How often would you use these
many rows are returned to a GlideRecord
capabilities?
Use encoded queries for complex query
conditions
Discuss: Why, when, and how often would you use the capabilities shown in this module.
GlideSystem
GlideRecord Labs
Events
Lab 8.1 Tracking Impersonations
Lab 8.2 Incident State Event
Script Includes
UI Actions
Flow Designer
Although any server-side script can generate an event, most will be generated by Business Rules or
Workflows.
Events are not actions but rather an entry in the Event Queue.
Logic must be written to respond to entries in the Event Queue and take action.
Event Response to
Event Queue
Generated Event
The Event Registry table records the Events that can be called and responded to. Although scripts
can call any Event, if it is not registered, no response will occur.
Unless otherwise specified, all user-created events appear in the default queue.
Optional
Event name – name used in script logic to generate the event. By convention the event name is
<table name>.<event name>. The table_name is not automatically added to the Event name and
must be added manually.
Table – database table for the event.
Fired By – list of scripts calling this event. This is used for troubleshooting only and not for event
processing. Whenever you add an event to a script, update this field.
Description – documents the event purpose. Be sure to put a meaningful description for future
reference. If you alter the meaning of an event, update this field.
Application – identifies the scope containing the event.
Queue – the event processing queue which manages this event. If left blank, the event is processed
by the default queue. User-defined queues should be all lowercase and use underscores to separate
words.
ServiceNow cannot respond to events unless they have been registered. The method used to
generate events can be passed any string as the event parameter. Events generated with
unregistered event names will be inserted in the event queue but no ServiceNow processes will
respond to the event queue entry.
CAUTION!
Do not overwrite the text index events process Schedule Item!
Overwriting the text index events process Schedule Item removes ServiceNow's ability to
process that baseline queue. Use Insert and Stay as soon as possible to save your new
Schedule Item.
When you are creating a queue, the value passed to the GlideEventManager() method must match
the value of the Queue field in the Event Registry.
By default, the scheduler checks for messages in this queue every 30 seconds. (Trigger type =
Interval and Repeat = 30 seconds.)
Sending an event to the text index events process queue could potentially delay processing of higher
priority events. For example, if an event is generated every time a record is imported, a large Import
Set could delay processing of the more important Priority1Event.
Use this feature only when there is a possibility of long Script Action Processing times or rapid
generation of events causing high volumes in the queues.
• Example:
gs.eventQueue("problem.myInsertedProblem", current, "Number: " +
current.number, "Created by: " + gs.getUserDisplayName());
parm1 and parm2 can be strings ("hello world"), properties (current.assigned_to), variables
(myString), or methods (gs.getUserID()).
The example shown calls the registered event problem.myInsertedProblem and passes it the current
object, the number of the current record, and the value of gs.getUserDisplayName().
• Example:
gs.eventQueueScheduled("problem.reminder", current, "Event time: " +
current.u_reminder, gs.getUserName(),
current.u_reminder);
The time parameter is set to a record field containing a Date/Time value. The event is generated at
the time passed in this field.
The example shown calls the registered event and passes it the current object, the string "Event
time:" + the value in the current.u_reminder field, the value of gs.getUserName(), and the date/time
for the event to be generated.
Created – date and time of the event for the locale of the machine running the ServiceNow
instance.
Name – name of the event.
Parm1 – event-specific value dependent on the event and the recipient.
Parm2 – event-specific value dependent on the event and the recipient.
Table – database table acted on by this event.
Processed – date and time the event was processed. This time reflects the locale of the machine
running the ServiceNow instance.
Processing duration – time taken to process this event in milliseconds.
Queue – processor queue name.
The Processed time should be within 30 seconds (or whatever the Interval is for the Schedule Item)
of the Created time.
Scripts can be set to execute whenever a particular activity occurs in the system, rather than at a
particular time. Navigate to System Policy > Events > Script Actions to create a new Script Action.
The event and current objects do not exist in the Condition script field. Testing for conditions using
these objects must be done in the Script field. Example: if(event.parm1 == 'itil').
• Lab 8.1
– Time: 10-15m
– Tracking Impersonations
• Practice writing a Script Action that reacts to an event.
• Lab 8.2
– Time: 10-15m
– Incident State Event
• Register, generate, and respond to an event
Lab Summary
You will achieve the following:
• Write a Script Action to the baseline impersonation.start event.
• Mark a Cloud Dimensions' Phase II requirement complete.
Business Problem
At Cloud Dimensions, IT Security is in place across all the systems in the Enterprise, due in large
part to many of the systems containing credit card data. It is the long-term goal for their
ServiceNow instance to also contain credit card data.
IT Security must show they are prepared to investigate security breaches. One of the
requirements is to be able to track when System Administrators impersonate other users in
their Production instance.
Project Requirement
Create an event to track impersonations and log the information. The IT Security team will use
the records to build a report.
b) Select New.
Log the name of the user doing the impersonation and the user being impersonated.
4. Select Submit.
3. End the impersonation. You should be logged in as the System Administrator when
this step is complete.
6. Examine Parm1 for the two events. What value does Parm1 have? Record the value
here:
__________________
_____________________________________________________________________
8. Why are there only two impersonation.start events in the last minute or two?
_____________________________________________________________________
_____________________________________________________________________
9. Open System Logs > System Log > Script Log Statements. Locate the two log
messages your Script Action wrote. Did the Parm1 and Parm2 values resolve
correctly? If not, debug and re-test.
Lab Completion
Good job! You have successfully created an event to track impersonations and log the
information.
Lab Summary
You will achieve the following:
• Register, generate, and respond to an event.
• Trigger the event by changes to the Incident State.
2. Select New.
4. Select Submit.
B. Trigger an Event
1. Create a new Business Rule.
Generate the incident.state.changed event and pass it the current object, the
previous incident state's display value, and the current incident state's display
value.
4. Select Submit.
b) Select New.
f) Select Submit.
d) Select Update.
c) Are the parm1 and parm2 values what you expected? If not, debug and re-test
the Business Rule.
a) Open System Logs > System Log > Script Log Statements.
Lab Completion
Well done! You have successfully registered, generated, and responded to an event. Use any
server-side scripting techniques to respond to any event you create.
• Use the Event Log to see the values of parm1 and parm2 in runtime and to check
when/if the event was processed
• Create queues for Events generated frequently
• Ensure new Script Actions are active
Discuss: Why, when, and how often would you use the capabilities shown in this module.
GlideSystem Labs
Lab 9.1 Classless Script Include
GlideRecord
Lab 9.2 Create a New Class
Ev ents
Lab 9.3 HelloWorld GlideAjax
Script Includes
Lab 9.4 Number of Group Members
UI Actions Lab 9.5 JSON Object
Flow Designer
In this module you will write, test, and debug Script Includes.
Application Scope
IMPORTANT
You should not modify the behavior of baseline Script Includes.
• Not many configuration options as a Script Include runs only when called
• Runs server-side
Must be called to run
• No default objects
• Data (parameters)
passed in from the
calling script
What executes when called
Name – name of Script Include. No spaces, no special characters. Format is very important!
API Name – The API name of the script, including the scope and script name.
Client Callable – select this option if client-side scripts can call the Script Include.
Application – identifies the scope of the Script Include.
Accessible from – sets the accessibility of the Script Include.
• All application scopes: sets the Script Include to be global, and can be accessed from any script.
• This application scope only: sets the Script Include to be private and can only be accessed by
other scripts in the same scope.
Active – select this option if the Script Include is executable. If this option is not selected the Script
Include will not run even if called from another script.
Description – (optional but highly recommended) documentation explaining the purpose and
function of the Script Include.
Script – script logic to execute.
IMPORTANT
A Script Include will NOT execute if there are spaces or special characters in its name.
Application Scope
Classless/on-demand Script Includes are not callable from the client-side even if the Client callable
option is selected.
Delete the code template automatically inserted in the Script field after the Script Include is named.
If a second function is included in the script, it is only available for use after the first function has
executed. This strategy is not considered best practice. If you wish to create a script with multiple
functions, it is better to define a new Class or extend an existing Class.
Most Script Includes, when called server-side, are called from Business Rules.
To use a Classless Script Include from a Business Rule, simply reference the function.
You will see later in this module how Class-based Script Includes are handled differently.
• Lab 9.1
– Time: 10-15m
– Classless Script Include
• Create, test, and debug a classless Script Include
Lab Summary
You will achieve the following:
• Create, test, and debug a classless Script Include to write logging messages for
server-side scripts.
2. Select New.
Name: logPropertyValues
Accessible from: All application scopes
Description: Lab 9.1 server-side logging
4. Delete the Script Include template code stub currently in the Script field.
4. Select Submit.
2. Select Submit.
3. Open System Logs > System Log > Script Log Statements. Do the Incident's
properties and values appear here? If not, debug and re-test.
5. Create a new Incident and populate the fields with the values of your choice.
7. Open System Logs > System Log > Script Log Statements. Do the new Incident's
properties and values appear here? Should they appear? Explain your reasoning:
_______________________________________________________________
_______________________________________________________________
8. Explain why a Script Include to write log data with an "on/off" parameter is useful
for debugging scripts:
_______________________________________________________________
_______________________________________________________________
9. Make the Lab 9.1 Script Include Logging Test Business Rule inactive.
10. Do you need to make the logPropertyValues Script Include inactive? Why or why
not? Is there a performance impact if it remains active? Explain your reasoning:
_______________________________________________________________
_______________________________________________________________
Lab Completion
Well done! You have successfully created a classless Script Include and called it from a
Business Rule.
Application Scope
Once a Script Include is named, a Script Editor Macro is automatically inserted in the Script field and
the Name is propagated throughout the script. If you change the Name of the Script Include, the
script will automatically update to reflect the change.
Type is for allowing any developer using your Script Include to identify the type of object it is. Search
Community for more information on the topic, quite a few blog articles have been written by
ServiceNow experts on this advanced subject.
You can also define variables and objects in the initialize() function as well.
In this example, the logged-in user's User [sys_user] record was retrieved.
• Lab 9.2
– Time: 20-25m
– Create a new Class
• Create, test, and debug a Server-Side Script Include
Lab Summary
PLEASE READ: The concept for this lab comes from a requirement many customers request
when implementing Asset Management. Every organization has their specific Asset
Management strategy, but for the purpose of this lab, this is the scenario you will practice
using existing demo data:
The Asset Location picker should only show relevant locations based on Asset Manager roles:
• Local-level Asset Managers can assign Configuration Items to locations in their
assigned Regions.
• Company-level Asset Managers can assign Configuration Items to their own
corporate locations.
• System Administrators can assign Configuration Items to all locations.
This lab presumes the following regarding demo data in Locations [cmn_location] table:
• Corporately owned locations are identified using an ACME organization in the
Company [company] field. Non-corporate locations listed in the Locations table are
never identified as an ACME company.
• Corporate locations are grouped by Regions. The Parent [parent] field in the
Location table is used to identify a location’s Region. Non-corporate locations listed
in the Locations table are never assigned to a Region.
• Only users with the proper permissions have 'edit' access to the Location field in
Configuration Item records.
These new Groups and Roles have already been created in the platform for this lab. Users have
also been added to each group for testing purposes.
Group: Asset Managers – New York Group: Asset Managers – Corporate
Role: asset_mgr_local Role: asset_mgr_corporate
User: Luke Wilson User: Howard Johnson
2. Select New.
Note: Notice every location is available for selection. (Close this pop-up window when you are
ready to proceed.)
Name: LocationsByRole
Accessible from: All application scopes
Description: Lab 9.2 Restrict Location Options
3. Select Submit.
2. Select New.
4. The record is read-only as the Location [location] field does not exist in the Printer
[cmdb_ci_printer] table. The hierarchy for this table in the platform is Base
Configuration Items [cmdb] > Configuration Items [cmdb_ci] > Printer
[cmdb_ci_printer].
Select the Click here link in the InfoMessage at the top of the form to open the
Dictionary Entry record for the Location [location] field in the Base Configuration
Items [cmdb] table. The record opens in a new browser window.
Note: The Scope name is not required if the Script Include is in the same scope as the Dictionary
Entry record. javascript:new global.LocationsByRole().forCMDB() works as well.
On the Attributes Related List, double-click the Tree picker’s Value field and update
it to false.
8. Select Update.
9. Close the browser tab you are currently on and return to the original browser tab
displaying the full view of the platform.
2. Select New.
Scroll to the bottom of the window. Record the total number of records: __________.
If you did not add any Locations to the baseline demo data, there should be 425
records in the list.
4. Impersonate Luke Wilson. A member of the Asset Managers – New York Group with
the asset_mgr_local Role, and his Parent Location (Region) is New York.
6. Select New.
Notice only the two New York locations are available for selection. If not, debug and re-test.
11. Select the magnifying glass to the right of the Location field.
Notice only North America corporate locations are available for selection. To be
sure, quickly scan through a few pages to confirm.
Also record the total number of records in the list now: _________. If you did not
add any Locations to the baseline demo data, there should now be 372 records in
the list. If not, debug and re-test.
12. End the impersonation. You should be logged in the System Administrator when this
step is complete.
Lab Completion
Great job! You have successfully created and used a server-side Script Include. This strategy
for restricting Locations was selected because it pushes the data to the client before the user
even opens a form, thus eliminating a round-trip visit to the server and back an onLoad()
Client Script would require.
Application Scope
Extending a Class means to add functionality (typically in the form of methods) to an existing Class
without modifying the original script.
Create a New Script Include/Class, reference an existing Class using the extendsObject() method to
include all its functionality, add script logic
In this example, the alertGreeting() method is created. When it is called, it returns the string “Hello
<name passed in from the client> !” to the calling script.
The code shown here would be wrapped in a function (onLoad, onSubmit, onChange) depending on
the type of Client Script.
In this example the GlideAjax object is used to call the Script Include and pass in parameters. The
reserved parameter sysparm_name tells GlideAjax which function in the Script Include to use. All
passed in parameters must start with sysparm_.
The getXML() method is passed the name of a callback function which parses properties and values
from the XML returned from the server. (Data is often returned as XML but can also be returned as a
JSON object.)
The getXMLAnswer() method can be used instead of getXML(). This method automatically extracts
the answer variable value from the returned XML. Example:
var objDesc = new GlideAjax('HelloWorld');
objDesc.addParam('sysparm_name','alertGreeting');
objDesc.addParam('sysparm_var1','Ruth');
objDesc.getXMLAnswer(HelloWorldParse);
The XML in this example was captured using Firebug and has been edited to fit on the slide.
• Client-side Script
var greeting = new GlideAjax('HelloWorld');
greeting.addParam('sysparm_name','alertGreeting');
greeting.addParam('sysparm_user_name',"Ruth");
greeting.getXML(HelloWorldParse);
function HelloWorldParse(response) {
var answerFromXML = response.responseXML.documentElement.getAttribute("answer");
alert(answerFromXML);
}
The client-side code shown here would be wrapped in a function (onLoad(), onSubmit(), or
onChange()) depending on its type.
userNames: function() {
var id1 = this.getParameter('sysparm_user_id1');
var id2 = this.getParameter('sysparm_user_id2');
var u1 = new GlideRecord('sys_user');
var u2 = new GlideRecord('sys_user');
if (!u1.get('employee_number', id1))
return '';
if (!u2.get('employee_number', id2))
return '';
The IdentifyTwoUsers object has a function called userNames which is passed two values:
• sysparm_user_id1
• sysparm_user_id2
The Script Include retrieves the records from the database for both sysparm_user_id1 and
sysparm_user _id2.
If the records both have a value in the employee_number field, the Script Include concatenates the
two employee numbers with a : (colon) and returns the string to the calling script.
• Client-side Script
var twoUsers = new GlideAjax('IdentifyTwoUsers');
twoUsers.addParam('sysparm_name', 'userNames');
twoUsers.addParam('sysparm_user_id1',g_form.source_id);
twoUsers.addParam('sysparm_user_id2',g_form.target_id);
twoUsers.getXML(userParse);
function userParse(response) {
var answerFromXML = response.responseXML.documentElement.getAttribute("answer");
var user = answerFromXML.split(':');
var confMerge = confirm('Merge ' + user[0] + ' --> ' + user[1] + '\nAre you sure?');
if(confMerge){
<additional script logic would go here…>
}
}
The client-side code shown here would be wrapped in a function (onLoad(), onSubmit(), or
onChange()) depending on the type of client-side script.
In this example, the answerFromXML variable from the response contains multiple pieces of
information separated by a colon. The statement var user = answerFromXML.split(':') breaks the
answer variable into an array called user with each element being whatever is between each set of
colons. In this case, user[0] contains the value from the beginning of the answer string until the first
colon, and user[1] contains the value from the colon to the end of string. Assume answer =
Matt:Miranda. In this case user[0] = ”Matt” and user[1] = ”Miranda”.
• Lab 9.3
– Time: 10-15m
– HelloWorld GlideAjax
• Create a Client Script that calls a Script Include
• Lab 9.4
– Time: 20-25m
– Number of Group Members
• Create a Client Script and Script Include that returns information
to the client
Lab Summary
You will achieve the following:
• Create a Script Include which extends the AbstractAjaxProcessor class.
• Create a Client Script to call the Script Include.
4. Select Submit.
4. Select Submit.
5. The first parameter in the script you just wrote is sysparm_name, it is a reserved
parameter name. What information does it pass to the Script Include?
_____________________________________________________________________
6. Other than beginning with a sysparm_ prefix, do additional parameters have to use
reserved parameter names?
_____________________________________________________________________
2. Did an alert appear? Was it populated correctly? If not, debug and re-test.
Lab Completion
Great job! You have successfully extended the existing AbstractAjaxProcessor class. The
alertGreeting() method you created in the HelloWorld Script Include expects a value to be
passed in when it is called. It then uses that value to build a string and return it to the client.
You then used the GlideAjax class in a Client Script to call the alertGreeting() method in the
new Script Include.
Lab Summary
You will achieve the following:
• Create a Script Include which:
§ Extends the AbstractAjaxProcessor
§ Return the number of members of a group.
• Create a Client Script that will:
§ Call a Script Include.
§ Pass a Group name to the Script Include.
§ Parse the response from the Script Include.
4. Select Submit.
4. Select Submit.
2. Select a group with members assigned to it. Record the group you selected here:
_______________________________
4. Change the value in the Assignment group field to the group you selected in step 2.
5. Did an alert appear? Was it populated correctly? If not, debug and re-test.
6. Change the value in the Assignment group field to IT Securities. (The IT Securities
group has no members baseline.)
7. Did an alert advise there are no members in this group? If not, debug and re-test.
_____________________________________________________________________
6. Change the value in the Assignment group field to the group you selected earlier in
the lab.
8. Make both the Lab 9.4 Number of Group Members and Lab 9.4 and Number of
Group Members (PRB) Client Scripts inactive.
Lab Completion
You have completed the lab and successfully extended the existing AbstractAjaxProcessor
class. The new countGroupMembers() method you created in the AssignmentGroupUtils
Script Include uses the passed in Assignment group’s sys_id in a GlideRecord query to count
the members of that Assignment group and return the information to the client.
You used the GlideAjax class in a Client Script to call the new method and use the value
returned from the server in an alert to inform the user how many members are in their
selected group.
type: 'CallerIncidents'
});
In this example, when the Script Include is called, the script first creates an empty array called
incArray.
It then uses the passed in parameter sysparm_callerID in a GlideRecord query to gather all of the
user’s Incident records.
The while loop builds an incDetails object using properties/values from the GlideRecord query and
puts that object into the incArray array.
The JSON.stringify() method is used to create a string from a JSON object (incArray) that is returned
to the calling Client Script.
<xml answer="[{"number":"INC0000014","priority":"2 -
High","shortDesc":"missing my home
directory"},{"number":"INC0000016","priority":"4 - Low","shortDesc":
"Rain is leaking on main DNS Server"},{"number":"INC0000038","priority":
"4 - Low","shortDesc":"my PDF docs are all locked from
editing"},{"number":"INC0000041","priority":"4 - Low","shortDesc":"My
cubicle phone does not work"}]"
sysparm_max="15" sysparm_name="callerIncidents"
sysparm_processor="CallerIncidents"></xml>
In the example shown, four objects are returned in the array sent back.
function CallerIncidentsParse(response){
//Build an array of objects from the JSON object and take action
var myObj = JSON.parse(response);
g_form.addInfoMessage('User has raised the following incidents:');
The client-side code shown here would be wrapped in a function (onLoad(), onSubmit(), or
onChange()) depending on the type of client-side script.
• Lab 9.5
– Time: 25-30m
– JSON Object
• Create a Client Script that calls a Script Include that will return a
JSON Object
Lab Summary
You will achieve the following:
• Use the Script Include and a copy of the Client Script you wrote in the previous lab.
• Modify the Script Include to return a JSON object containing an array of Group
members
• Modify the Client Script to dynamically select a group member from the JSON object
to assign to an Incident.
• Complete a Cloud Dimensions' Phase II requirement.
Business Problem
A few IT analysts are reporting the same individuals are continually being assigned Incidents on
their teams. They would like to ensure support responsibilities are spread across the team, as
everyone is busy working on other items in addition to their support responsibilities.
After some discussions, management has agreed to implement a strategy that will randomly
assign analysts to Incidents, ensuring everyone has a turn.
Project Requirement
To implement this strategy, two scripts will be required:
1. First, create a Script Include to randomly select an analyst from the identified
Assignment group, and then return that name to the calling Client Script.
Lab Dependency: This lab builds on the scripts created in Lab 9.4 Number of Group
Members. Please complete the scripts in that lab before proceeding.
2. Place your cursor after the comma at the end of the countGroupMembers function.
Press Enter <return> on your key board two times to create some blank lines. (The
blank lines will leave some space between functions for easy readability.)
3. Examine the pseudo-code for the new method you will ADD to the Script Include:
5. Select Update.
2. Select Insert and Stay on the form's Context menu to make a copy of the record and
remain on the form.
a) Modify the statement calling the method name to call the assignAnalyst
method.
ii. Use the JSON.parse() method to create an object from the returned JSON
formatted string.
iii. Add an 'if' statement to check if the array has elements. Generate a
random number and make the assignment.
iv. Add an else statement to clear the assigned_to field and advise if the
group has no members.
6. Select Update.
2. Examine the value of the Assigned to field. Record the value here:
___________________Change the value in the Assignment group field.
3. Was the Assigned to field populated with the name of an Assignee from that group?
If not, debug and re-test.
4. Record the name of the analyst currently in the Assigned to field here:
_________________________
5. Change the value in the Assignment group field to IT Securities. (The IT Securities
group has no members baseline.)
6. Did the value in the Assigned to field clear? If not, debug and re-test.
7. Did an alert advise there are no members in this group? If not, debug and re-test.
8. Make the Lab 9.5 Assign Analyst Client Script for this lab inactive.
Lab Completion
Fantastic! You have successfully added a second method to an existing Script Include. The
assignAnalyst() method uses the passed in Assignment group’s sys_id in a GlideRecord query
to build an array containing all the sys_ids of the group members. It then returns the object
to the client.
You used the GlideAjax class in a Client Script to call the new method and use the returned
object to randomly assign incidents to group members ensuring the group’s work is shared
fairly.
Incident Task
Incident
State Value Constant
(task)
State
(incident)
The IncidentStateSNC and IncidentState Script Includes provide State constants for use in scripts.
• Script Includes with SNC in the Name are meant to be read-only. (This ensures the SNC Script
Includes are updated during upgrades.)
• To impose pre-requisites or limits for moving from one state to another, you can incorporate
new logic in the IncidentState Script Include.
• To override a function defined in an SNC Script Include, copy that function to the paired version
of the Script Include that does NOT contain SNC. Paste and customize the function there.
State Models currently exist for the Incident and Change applications. Visit docs.servicenow.com
and search for the following articles for more information on the State Model.
• State model mapping
• Add a state to the state model
• Scripts modified with Incident Management – Core
• Script includes installed with Incident Management – Core
• Installed with Change Management – State Model
• Update change request states
• You have reviewed many ways to get information from the server in class
• The recommended methods are
– g_scratchpad
• Sent once when the form loads
– GlideAjax
• Dynamically triggered when the client requests information from the server
As you learned in previous modules, GlideRecord and g_form.getReference() are also available for
retrieving server information. They have a slightly higher performance impact. Both methods
retrieve all fields in the requested GlideRecord when most cases only require one field.
Application Scope
Use the Accessible from field to make a Script Include accessible from all scopes.
• Only applies when applications are installed from the ServiceNow App Store
• Sets the level of protection for the application file
• Protection policies safeguard intellectual property by making the file
read-only or Protected (not visible)
Protection policies do not prevent other developers on the application development instance from
viewing or editing a Script Include.
Protection policies are not applied when applications are published and migrated to an instance
using an Update Set.
For the instance on which an application is developed, use Access Controls and/or roles to restrict
User ability to see and edit Script Includes. Protection policies do not apply in this case.
– To call a Script Include in another scope, prepend the Script Includes name with its
unique scope namespace to distinguish it from other Script Includes with the same name
var travSched = new x_cld_travel.ItineraryConflict();
var switches = new global.ArraysUtils();
Every custom application has an application scope that is defined by its namespace.
In the example on the left, two Script Includes are developed for the Travel Management
application.
• VendorUtils – methods for managing vendors, set to be accessible from all application scopes.
• ExpenseUtils – methods for managing and processing travel expenses, set to be accessible only
to other scripts in the Travel Management scope.
On the right, a Business Rule named ReserveProjector has been developed for a Loaner Equipment
application:
• The Business Rule script instantiates the VendorUtils Script Include in the Travel Management
scope to access its confirmVendor method. As this Script Includes' Accessible from value is set
to All application scopes, the Business Rule is permitted to use the method.
• Later in the Business Rule script, there is an 'if' statement to determine if the hardware loaned
to employees needs to be replaced with new equipment. The Business Rule instantiates the
ExpenseUtils Script Include to access its submitExpense method. As this Script Includes'
Accessible from value is set to This application scope only, access is denied.
JSON objects pass data as arrays or objects •How often would you use these
capabilities?
Privately scoped Script Includes can only be called by
other scripts in the same scope
Discuss: Why, when, and how often would you use the capabilities shown in this module.
Business Rules
GlideSystem
GlideRecord Labs
Ev ents
Lab 10.1 Client UI Action – Priority 1 Incident
Lab 10.2 Server UI Action – URL Redirect
Script Includes
Lab 10.3 Client and Server UI Action – Update Problem
UI Actions
Flow Designer
In this module you will practice writing, testing, and debugging UI Actions.
UI Actions put buttons, links, and context menu items on forms and lists making the UI more
interactive, customizable, specific to user activities, and applicable to business requirements. Scripts
take action when buttons, links, or context menu items are selected.
To prevent a button from appearing at the bottom of a form, set the glide.ui.buttons_bottom
system property to false.
Add UI actions to forms and lists in the same scope, as well as to forms and lists that allow UI
Actions from another scope to run on them.
IMPORTANT
If you think you need to modify a baseline records, be sure to think about the following,
ask yourself a few questions, and act accordingly.
• Carefully consider the customization
• Will no code changes work?
• Is customization necessary?
• Modify the baseline record
• Review and revert the skipped file after an upgrade
If the condition field has no value, the script will execute whenever the trigger criteria is met.
The example shown works with a condition to offer a user the opportunity to launch the RIM Tech
Support website in a new browser window if an Incident's CI is Blackberry (see preceding slides for
trigger and condition).
Protection policies are not applied when applications are published and migrated to an instance
using an Update Set.
For the instance on which an application is developed, use Access Controls and/or roles to restrict
User ability to see and edit UI Actions. Protection policies do not apply in this case.
For example, a Close Incident button might be available only to group managers or should appear
only on Incident forms if the state is resolved.
If the Condition field has no value the script will execute whenever the trigger criteria is met.
1. Select Client
trigger option
2. Enter function
name in
Onclick field
3. Write function
in Script field
Use client-side methods when scripting for execution within the browser. The script has no access to
server-side objects, such as current, or methods, such as gs.log.
Only UI Actions included on a form can be called. For example, the Edit Homepage UI Action's link
does not appear on the Incident form and could not be called from a UI Action for the Incident form.
The first parameter is the control (will have the value null when calling UI Actions), the second is the
form, and the third is action name.
UI Actions run on the server-side when the Client option is not selected.
When the UI Action is called a second time the Onclick function will not execute because the
button/link/menu item was not physically selected a second time. Any code not enclosed in a
function is executed. In this case, the if(typeof window == 'undefined') statement runs and the
server-side function is called.
• Lab 10.1
– Time: 15-20m
– Client UI Action – Priority 1 Incident
• Create, test, and debug a UI Action
• Lab 10.2
– Time: 15-20m
– Server UI Action – URL Redirect
• Create, test, and debug a server-side UI Action
• Lab 10.3
– Time: 15-20m
– Client and Server UI Action – Update Problem
• Create, test, and debug a UI Action that executes on both the
client and server-sides
Lab Summary
You will achieve the following:
• Create a UI Action requiring confirmation before submitting a Priority-1 Incident.
A. Creating a UI Action
1. Open the UI Action list: System Definition > UI Actions.
B. Testing
1. Create a new Incident.
2. Set the Priority to Critical by setting the Urgency and Impact fields each to High.
4. Did the confirmation dialog box appear? If not, debug and re-test.
5. Select the OK button in the confirmation dialog box. Was the incident submitted? If
not, debug and re-test.
6. Create another new Incident and set the Urgency and Impact to High.
8. Select the Cancel button in the confirmation dialog box. Was the Incident
submitted?
Lab Completion
Congratulations on completing the lab!
Lab Summary
You will achieve the following:
• Create a server-side UI Action accessible only from the Self Service view that allows
a caller to verify their user information is correct.
A. Creating a UI Action
1. Create a new UI Action.
6. Select the Edit button in the UI Action Visibility Related List at the bottom of the UI
Action form.
7. Select the Self Service view from the Collection slushbucket and Add it to the UI
Action Visibility list.
B. Testing
1. Create and Save a new Incident.
2. Do the Check User Info button and link appear on the form? Should they? Explain
your reasoning.
___________________________________________________________________
___________________________________________________________________
9. What page loads after the User record is updated? Is it the User list page? Why or
why not? Explain your reasoning.
___________________________________________________________________
___________________________________________________________________
Lab Completion
Congratulations on completing the Server UI Action – URL Redirect lab!
Lab Summary
You will achieve the following:
• Create a UI Action that executes on both the client and server-sides, retrieves the
problem_id from an Incident, and updates the related Problem’s Work notes.
A. Creating a UI Action
1. Create a new UI Action.
4. Write the UI Action script. If needed, refer to the "Client and Server UI Actions"
slide’s stub code.
2. Located the Related Records Tab and Assign a Problem to the Problem ID field. Note
the Problem number here:
________________________________
5. Examine the Problem’s Activity history. Does your message appear in the history? If
not, debug and re-test.
Lab Completion
Congratulations on completing the lab!
Discuss: Why, when, and how often would you use the capabilities shown in this module.
GlideSystem
GlideRecord Labs
Ev ents
Lab 11.1 Build a Flow
Lab 11.2 Trigger a Flow with a Script
Script Includes
Lab 11.3 Add a Script to a Flow
UI Actions
Flow Designer
Script-Triggered Subflow
Flow Designer and Workflow can be used at the same time in an instance. Understanding what
process fits the needs of your company can aid you in a decision. As of the London release, below
are some scenarios for Flow Designer or Workflow. Remember that even though it is suggested
here to use one method or another, you may still be able to accomplish a task using Flow Designer
or Workflow.
Flow Designer
Service Catalog Action Plan
• Approvals - Flow Designer has reimagined Approvals for a much more usable authoring
experience. Flow Designer is a good fit for approval flow associated to a catalog item
• Flow with Stages to report progress status to user
• Standard task creation or record updates
Record updates
• When you need to interact with a record, or related set of records, and make updates. Flow
Designer provides very intuitive ways to handle record updates, and working with related lists
• The new approval authoring method for Adding Approvals to a record (Service Catalog item,
Incident, or any) in Flow Designer is much improved way of dealing with approvals
IntegrationHub
• Slack, Teams, Active Directory, Azure AD, and more… (More integrations in the future.)
Action Designer – alternative to Script Include
• When you want to build a reusable component(s) (build once, reuse in flows)
Workflow
• Complex branching and parallel processing – e.g. complex catalog workflows
• Service Level Management (SLA Timer)
• Passwords must be masked
• Existing orchestration integrations
Flow Designer is a Now Platform feature that enables rich process automation capabilities in a
consolidated design environment. It enables process owners to use natural language to automate
approvals, tasks, notifications, and record operations without having to code.
IMPORTANT
Permission to use Flow Designer and view flow execution is controlled by assigning the
flow_designer role to users. Before you give a process owner this role, understand that
you are giving the user access to all tables and database operations which is equal to an
admin role.
The welcome page has links to Flows, Subflows, Actions, Flow Executions, Help, and New.
• A Flow is an automated process consisting of a sequence of actions and a trigger. Flows automate
business logic for a particular application or process.
• A Subflow is a sequence of reusable actions that can be started from a flow, subflow, or script.
• An Action is a reusable operation that enables process analysts to automate Now
Platform features without having to write code.
• Flow execution is a list of associated execution detail pages. Each record is created when a flow
runs. Process analysts can view the information the system stores about the configuration and
runtime values produced.
• The Help tab has resource links to Documentation, Videos, and Community Discussion.
• The New link uses a dropdown to allow you to create a New Flow, New Subflow, or New Action.
Active
Indicator More Actions
Flow Data
Trigger
Actions
Notifications
This example shows the Flow Editor after a Flow has been selected.
• House Icon - returns you to the Landing page.
• Flow Tabs – allows you to work on multiple flows; you can select the tab that you want to
work on.
• Plus Icon – selecting the icon will allow you to create a new Flow, Subflow, or Action.
• Indicator – The text will tell you if you are working on Flow, Subflow, or Action and if the
component of a flow is read only. Flows will have a gray (inactive) or green (active) dot.
• Title – Shows the flow you are currently working on.
• Status – Indicates if the flow is Draft.
• Scope – It is encouraged to use flow designer in a scoped application.
• Properties - Edit flow properties e.g. description and protection policy.
• Test - Simulate a trigger and execute the flow.
• Executions - List executions associated with this flow to open operations.
• Save - Save a draft of the Flow, Subflow, Action.
• Activate - Activate this flow and make the trigger live.
• Three Dots - open more actions that are specific to the flow, subflow, or action you are
working with.
• Trigger - specifies the conditions that start the flow. When the trigger condition is true, the
system starts the flow.
• Actions – The section groups sets of reusable business logic that produces a specific outcome
when provided with its input values.
• Flow Data - any data gathered or generated as variables will be available in the data pane.
Each variable has its own pill. The pill can be dragged and dropped on an action input or
output.
• Notifications – Previous activity Information.
The trigger specifies the conditions that start the flow. When the trigger
condition is true, the system starts the flow.
When will
this flow
start
Where to
monitor for
changes
Why this
flow will start
Creating a trigger for a flow will require When the flow will start, Where this flow will monitor for
changes, and Why this flow will start.
Unlike a Scheduled and Application Trigger Types, a Record Trigger Type requires:
1. Table to monitor - In this example we have chosen the incident table as the place to look at
for conditional changes. Choose the appropriate table.
2. Condition that starts the flow - Use the condition builder the same way you filter for a list.
All conditions created in the condition builder must be met.
Actions can be anything from creating tasks, looking up records, or sending email. Flow designer
has a number of core actions that can be used and custom actions that can be created.
• A core action is a ServiceNow-provided action available to any flow that cannot be viewed or
edited from the Action Designer design environment.
• Custom actions can be viewed or edited from the Action Designer design environment. The
custom actions always use the same configuration when added to a flow.
Flow Logic is a way to control what action steps are included or bypassed based or your criteria.
• The If conditional statements check if a condition is met before executing or skipping an action.
• The For Each Flow Logic loops through a list of records, supplied by flow data, to apply actions
for each record that meets the condition specified. Creating a Nested For Each loop requires
you to understand how many flow transactions this will generate and its duration. Nested For
Each loops are discouraged as they may cause the flow transaction quota rule to stop a flow
after an hour.
Subflows are a sequence of reusable actions that can be started from a Flow, Subflow, or Script.
Subflows are very similar to flows, but there are some differences.
• A trigger is not used to start a subflow.
• Subflows can use inputs form a parent flow.
• Subflows can return outputs to the parent flows when the subflows ends.
• Flows store any data gathered or generated as variables in the Data panel.
• Each variable has its own Pill that Flow designers can use to drag-and-drop
the variable value to an action input or output.
The variable with Trigger data is
stored as a Pill in the Data pane
As you create additional actions, additional Pills will be created. You can use the Pills in Actions,
Flow Logics, and Subflows.
Above, a pill being used with an Action. Below is an example of Pills being used with Flow Logic and
Subflows:
Flow Logic
The Trigger Data Pill is
used in an If conditional to
check the trigger incident
record’s priority.
Subflow
The Subflow is using the Pill
from a previous Action as
input. Subflows should be
created for reuse. This
modular design can save
you from creating
repetitive Actions across
several flows.
• Lab 11.1
– Time: 15-20m
– Flow Designer: Build a Flow
• Build a simple flow
Lab Summary
You will achieve the following:
• Build a flow that responds to the change in priority of an incident.
• Test the flow within the Flow Designer.
Scenario
When an incident is created or updated with a priority of 1 - Critical, management would like
for the incident to be assigned to the Incident Management group first.
Pre-Requisite
Since this is your first flow and you will test the result in flow designer, these system properties
will enable flow engine debug messages and show system logs within the Flow Execution
Details page.
9. To the right of Condition, select the + Add Filters and set the drop down to the
following:
Priority - is - 1-Critical
10. Select For each unique change on the Run Trigger drop-down.
12. In the Actions section, select the + symbol or Click to add an Action, Flow Logic, or
Subflow link.
13. From the buttons Action, Flow Logic, and Subflow, select the Action button.
Note: The Action menu has various Action Categories and the corresponding Actions. As you
look at each Action, information will be shown in the description section. Be sure to read the
description, so you choose the correct Action for your flow.
14. With the ServiceNow Core category highlighted, select the Update Record Action.
16. Move down to Fields and select the + Add Field Value button.
20. Select the Activate button and Select the OK button when the Confirm Flow Active
dialog box is shown.
Note: You should only test a flow in a Dev or Test instance, not a Production instance. Record
changes caused by the test of a flow or integration call are real.
1. With the Incident Changed to P1 flow open, select the Test button.
2. In the Test Flow dialog box, select the Record field and choose an incident.
4. After the flow process completes, open the Execution Details tab with the Flow has
been executed. To view the flow, click here link.
5. The Execution Details tab provides data and links about what occurred during the
test. Review the items below to understand what occurred with its execution.
• Trigger and Actions - Select the Trigger or the Actions to expand the sections.
Review additional Information about what occurred when the trigger or action
processed.
• Open Flow Logs – View the flow logs of what occurred during the test.
• Open Current Record – Open the form of the record to see the changes.
• Logs – The drop-down shows the logs that were recorded during the flow
execution.
Note: The large amount of detailed information, gathered in one place, about the flow
execution is convenient and helpful. Benefits of the Execution Detail become more apparent
with larger flows.
7. Was the Test Run completed the way you expected? Why or why not?
_________________________________________________________________
10. Select the Deactive button and select Ok to Confirm Flow Deactivate.
Lab Completion
Good job! You have successfully created a flow and tested the execution of that flow.
Script-Triggered Subflow
A subflow is a container of automated steps that a process analyst can use in a flow. A process
analyst may need to post a message in Slack, query a Now platform table, or create approvals with
emails, but they may not be familiar with the details to accomplish these tasks. By selecting a
subflow with multiple steps, intensive calculations, or complicated connection strings, a process
analyst can quickly take advantage of the power of a subflow and then incorporate it within the flow
they are creating.
Subflows that automate generic business logic that helps process analysts and low code admins to
not only integrate the capabilities of a Subflow into a flow, but into every additional flow that is
created. The ability to reuse the functionality over and over in multiple applications or processes
increases the speed at which a flow is built and its ease of creation.
• Create the subflow before you create the script to call it.
• Subflows must be published. Unpublished Subflows will not show up in your actions section
and can not be called from code.
• The script you use to call a subflow can be a Server script or Client script.
• Each API has different functionality for the environment that it was designed for, so use the
Code Snippet Generator to select the API for your application
• The Internal name of a subflow will be used. This is created by the designer and can be found
on the Landing Page -> Subflow list. The internal name is a lowercase, no-spaces version of
your subflow name
• Inputs should be Name-value pairs. If the subflow calls for a reference type value, use a
GlideRecord object as the value.
IMPORTANT
With all the new ways to call a Flow/Subflow, the following calls have been deprecated:
• sn_fd.Flow
• sn_fd.Subflow
sn_fd namespace to access the Flow API Application Scope Internal name
Note: The timeout for the blocking mode is the maximum time this Flow / Action will run before it is
cancelled. If you do not add a timeout, the system default value is used which is determined by the
property com.glide.hub.flow_api.default_execution_time . The default value is 5000 ms.
IMPORTANT
The Input map keys need to include data that the flow’s record triggers are expecting.
Client-side API
GlideFlow.startFlow(String <scoped_name>, Object inputs);
GlideFlow.startSubflow(String<scoped_name>, Object inputs);
GlideFlow.startAction(String <scoped_name>, Object inputs);
Client-side API
Pros: Allows front-end access to Flows / Subflows / Actions
Cons: Not immediate as JavaScript promise objects are returned which represents the eventual
result of an asynchronous operation.
Note: Server-side script is rigidly controlled compared to the Access to Client-side script. When
using Client side script to execute a Flow, Subflow, or Action, there must be a new
“client_callable_flow_object” ACL type assigned to it. If this is not done, by default access will be
denied. All ACL management is handled with the “Manage Security” menu in Flow Designer.
• Lab 11.2
– Time: 20-25m
– Flow Designer: Trigger a Subflow with a Script
• Build a UI action that will trigger a subflow
Lab Summary
You will achieve the following:
• Build a Subflow that can be triggered by a UI action.
• Create a UI Action that triggers the Subflow.
• Execute the UI Action that calls a Subflow and creates an Incident Task with values from
the Incident.
Scenario
The Incident Management group has noticed some incidents did not need to be marked as a
Priority 1-Critical. Since all critical Incidents are taken seriously and are reviewed by upper
management, the service desk and the Incident Management group has decided that service
desk employees needed another option. Incidents that are a possible candidate for Priority 1-
Critical should be reviewed before being set to the highest Priority. Here is the solution:
• An Incident Task will be created and assigned to the Incident Management group.
• Since the incident could be time-sensitive, a UI action will quickly create an Incident
task record and populates the form.
• Name: triggerbyui
• Application: Global
• Description: Subflow that creates an Incident Task for Incident Management to
review
5. After the Subflow is saved successfully, locate the INPUTS & OUTPUTS section, and
select the + Click to create the inputs & outputs of your subflow.
7. Select the Label Field that is marked variable and change the wording to number.
8. Select the Type drop down. Choose the Reference > Type and Complete the
Reference by selecting the Incident [incident] table.
9. Select the symbol twice, and add the following Inputs with the information:
• Label: short_description
• Type: String
• Label: description
• Type: String
11. Locate the Actions section and select the + Click to add an Action, Flow Logic, or
Subflow.
15. Select the + Add Field Value and add the following fields and values
Field Value
Incident Select the number pill from the Data Panel -> Subflow
Inputs and drag the pill to the empty field.
Priority Select 3 – Moderate
Short Description Type Possible Priority 1-Critical:. Select the short_description pill
from the Data Panel -> Subflow Inputs and drag the pill to the field.
Assignment Group Select the Incident Management group
Description Select the description pill from the Data Panel ->
Subflow Inputs and drag the pill to the empty field
2. With the Possible 1-Critical Incident Subflow open, select the Test button.
5. Wait for the “Processing Test Subflow” to complete and then select the Subflow has
been executed. To view the subflow, click here.
6. In the Execution Details, select the Subflow Inputs & Outputs and the Create
Record to expand those sections and review test results.
7. Was the Test Run completed the way you expected? Why or why not?
_________________________________________________________________
8. Locate the Subflow Input Variable Name number and select the link to incident
number you chose.
10. Add the Incident Task related list to the form by selecting the
Additional actions menu button.
12. On the Configuring related lists on Incident form, scroll down the Available slush
bucket until you locate the Incident Task -> Incident table, select the table to
highlight the table, and select the right arrow button to move the table to the
Selected slush bucket.
14. On the Incident form, scroll down to the related list, select the Incident Tasks tab,
and verify that the Incident Task has been created with inputs you entered.
3. Select New.
• Use a GlideRecord object for the input of Reference type as the value
• Create Name-value pairs that define Subflow inputs.
• Use the sn_fd namespace to access the Subflow API.
• Use startAsync(String scopeName.subflowName, Map inputs) to start the Subflow.
• Store the the Sys ID of the flow execution as contextId
10. Use the Server Script that is generated in the UI Action Script field.
3. Verify the Incident Task has been created in the Related Lists.
Note: The Incident Task may not be visible immediately. Refresh the incident if does not show
up.
Lab Completion
Congratulations on completing the lab! You have successfully called a Subflow from a script.
Script-Triggered Subflow
The last section in this Flow Designer module is creating an Action. It follows in the same style as
Flow and Subflow. This is a top-down down approach that lowers the barrier to entry for process
owners and low code admins to create Actions. These roles will use the s et of core action steps to
automate Now Platform processes. Also, subject matter experts, scripters, and developers can use
the core action steps to quickly incorporate tedious tasks into a Custom Action. This leaves more
time to focus on the other aspects of creating Flows.
Reusability
Reusability has been stressed in this module. You may recall from the Script Include module, script
includes are consider a write once use many times component. A key difference between the reuse
of Script Includes and Actions is the accessibility. Script Includes need to be called from code. Flow
Designer interface makes code reuse easier by making the Action easily discoverable. Think about
how other departments within your organization can utilize the same Actions you create.
IMPORTANT
The action_designer role is required to build Custom Actions.
Just like the subflow you created in the previous lab, inputs and outputs in an Action function the
same way. The Input of an Action allows data, of various types, to pass to the Action Steps. After
processing the data, Information is relayed back to the flow. This returning data may be used in
additional subflows or actions.
Just as Flow designer has a number of core actions, several core action steps have been provided to
help with building an action.
Previous modules have stressed the importance that scripts should only be created when a feature
or functionality is not available in a baseline instance. Action Designers should follow this same
advise when a Script Step is created.
IMPORTANT
The Script step provides the ability to create integrations with third party systems, but this
functionality requires the IntegrationHub plugin to be activated. If you are creating a script
for your instance only, the plugin is not required.
Action Input
and Output
Variables
The Javascript steps include separate Input and Outputs Variables. A Script step Input Variable will
need to be created, named, and an Action Input Variables data pill added to the Value field to make
the Action Input Variable data accessible to the script. Also, a Script step Output Variables can be
created and named to return any results back to the action. The Script Step Input and Output
Variable can be referenced in the script with the inputs and outputs prefix.
• Lab 11.3
– Time: 20-25m
– Flow Designer: Add a Script to a Flow
• Build a custom action that uses a script step.
• Build a flow that uses a custom action
Lab Summary
You will achieve the following:
• Build a custom action that uses a script step
• Build a flow that includes the custom action
Note: Visit the knowledge base for the “Module 11 - Student Resource”. The variables are
available to copy and paste. The “Report” variable will get you started, but will need to be
updated with the correct variables.
Scenario
The Priority 1-Critical has been resolved. Since the critical incidents are reviewed by
management, a request has been made for an After Action Report to be added to the record’s
work notes. Data should be used from the incident to make a brief summary.
5. Select Submit.
Label Type
Assigned To String TIP FROM
Assignment Group String THE FIELD:
Created on Date/Time This lab has several
Created By String inputs and longer
Resolved Date/Time text portions than
Resolved By String other labs. Use the
Number String Student Resources
Caller String file to copy and
Configuration Item String paste text, so you
Resolution Code String can focus on
Resolution Notes String scripting.
Short Description String
9. On the Select Step to add window, locate the Utilities section and select the Script
Step.
10. Under the 1. Script step section, select the + Create Variable.
11. Add the names below and drag the data pills to the values to create Script step Input
Variables.
Name Value
assigned_to action ->Assigned To
assignment_group action ->Assignment Group
created_on action ->Created on
created_by action ->Created By
resolved_at action ->Resolved
resolved_by action ->Resolved By
number action ->Number
caller_id action ->Caller
cmdb_ci action ->Configuration Item
closed_code action ->Resolution Code
close_notes action ->Resolution Notes
short_description action ->Short Description
Note: Do not use System Variable names for Input Variables. Names like sys_created_by or
sys_created_on disappear when saved. No warning message is given.
12. Under the Output Variables, add the Name Payload and the Type String.
13. Examine the pseudo-code for the script you will write:
• Create variables for the Create and Resolved Date Time Inputs
• Calculate the difference between Create and Resolved in days
• Create a report variable that will hold the After Action Report
o Include the calculated number of days in the report
3. After the flow is saved successfully, select the + Symbol or Click to add a Trigger.
6. In the Actions section, select the + symbol or Click to add an Action, Flow Logic, or
Subflow.
7. From the buttons Action, Flow Logic, and Subflow, select the Action button.
8. With the Global category highlighted, select the Lab 11.3 Custom Action Script
Action.
TIP FROM
9. Select the Data Pill Picker ( ) or Data Panel to dot- THE FIELD:
walk to the data for each Action Input.
The Data Pill Picker
Note: To dot-walk to data in the Data Panel, look for the can be faster than
right arrow( )next to the Data Pill. Select the right arrow the mouse to dot-
and data from that table is shown below the pill. walk to the data you
need. Use the arrow
To dot-walk to data in the Data Pill Picker, select the keys and type the
location of the data. In this case, it will be the Trigger –
field name for
Record Updated. Select a right arrow( ) of referenced data.
navigation.
When you have drilled down to the table, use the search bar
to narrow the fields shown.
12. Select the + symbol or Click to add an Action, Flow Logic, or Subflow.
13. From the buttons Action, Flow Logic, and Subflow, select the Action button.
14. With the ServiceNow Core category highlighted, select the Update Record Action.
17. Select and drag the Lab 11.3 Custom Action Script After Action Report data pill to
the Fields value field.
3. Select Save.
6. Use the number from the Incident created in the Record field.
8. After the flow process completes, open the Execution Details tab with the Flow has
been executed. To view the flow, click here link.
10. Return to the Incident created. Was After Action Report in the Work notes
activities?
Lab Completion
Good job! You have successfully created a flow and tested the execution of
that flow
Discuss: Why, when, and how often would you use the capabilities shown in this module.
4810 Eastgate Mall, San Diego, CA 92121, USA • (858) 720-0477 • (858) 720-0479 • www.servicenow.com