0% found this document useful (0 votes)
14 views

Scripting London

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Scripting London

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 481

ServiceNow

Scripting in ServiceNow
Fundamentals
participant guide
© COPYRIGHT 2018 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.

© 2018 ServiceNow, Inc. All Rights Reserved


Scripting in ServiceNow
Fundamentals
Table of Contents
Module 1: Scripting Overview ..................................... 5
Lab 1.1: Using the Syntax Editor....................................... 35
Lab 1.2: Syntax Checking ................................................ 40
Lab 1.3: Explore Scripting Resources .............................. 59

Module 2: Client Scripts ............................................... 67


Lab 2.1: Two Simple Client Scripts ................................... 85
Lab 2.2: g_form and g_user ............................................. 103
Lab 2.3: Debugging Client Scripts................................... 116
Lab 2.4: Client Scripting for Mobile ................................. 131
Lab 2.5: Client Scripting with Reference Objects ......... 143

Module 3: UI Policies .................................................... 155


Lab 3.1: Incident State Resolved/Closed....................... 166

Module 4: Catalog Client Scripts & Catalog UI Policies ........179


Lab 4.1: Control Variable Choices Catalog Client Script
192
Lab 4.2: Control Out of State Shipping Catalog UI Policy
198

Module 5: Business Rules ............................................. 207


Lab 5.1: Debugging Business Rules ................................. 244
Lab 5.2: Current and Previous ......................................... 253
Lab 5.3: Display Business Rules and Dot-walking ........... 257

Module 6: GlideSystem ................................................ 265


Lab 6.1: Setting the CAB Date ........................................ 277
Lab 6.2: Re-open Problem Date Validation .................. 280

© 2018 ServiceNow, Inc. All Rights Reserved


Module 7: GlideRecord................................................ 289
Lab 7.1: Two GlideRecord Queries ................................. 310
Lab 7.2: RCA Attached: Problem and Child Incidents 315
Lab 7.3: addEncodedQuery() ......................................... 319

Module 8: Script an Event ............................................ 327


Lab 8.1: Tracking Impersonations.................................... 338
Lab 8.2: Incident State Event........................................... 341

Module 9: Script Includes ............................................ 347


Lab 9.1: Classless Script Include ...................................... 358
Lab 9.2: Create a New Class ........................................... 366
Lab 9.3: HelloWorld GlideAjax ......................................... 381
Lab 9.4: Number of Group Members ............................. 384
Lab 9.5: JSON Object ....................................................... 393

Module 10: UI Actions .................................................. 409


Lab 10.1: Client UI Action ................................................. 426
Lab 10.2: Server UI Action ................................................ 428
Lab 10.3: Client and Server UI Action ............................. 431

Module 11: Flow Designer Scripting............................ 437


Lab 11.1: Build a Flow ....................................................... 448
Lab 11.2: Trigger a Subflow .............................................. 456
Lab 11.3: Add a Script to a Flow ..................................... 469

© 2018 ServiceNow, Inc. All Rights Reserved


Overview
© 2018 ServiceNow, Inc. All Rights Reserved 5
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 6
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 7
ServiceNow provides the ability to customize an instance using JavaScript (based on Mozilla Rhino).

JavaScript, popularized by Yahoo, is the most prevalent scrip?ng language on the web. It is object-
oriented, runs within a browser, and does not need a license.

Rhino is an open-source implementa?on of JavaScript wriFen en?rely in Java. It is typically


embedded into Java applica?ons to provide scrip?ng to end users.

The JavaScript engine used to evaluate scripts in ServiceNow supports the ECMAScript5 standard
and is based upon Rhino version 1.7 R5.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 8
Remain current with ServiceNow's ongoing development:
• Check ServiceNow's Product and Developer documenta?on before developing anything new.
• Stay current on what has changed from release to release.
• Check the most recent version's release notes.
• AFend release mee?ngs.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 9
Examples of when you should script:
• Update related record(s)
o Cascade a comment from a master incident to its children.
o Upda?ng the ownership of a Configura?on Item (CI) aVer a Change Request.
• Approval Strategies
o One or all does not meet your business requirement.
o Approvers need to be set dynamically.
• Show/hide a form sec?on.
• Scan a list of CIs to dynamically determine risk based on cri?cality.
• Query database.
• Customize widgets.
• Change default behaviors.

The list of examples shown above is representa?ve of typical uses for scrip?ng. There are, of course,
no limits as to what one can do with JavaScript in ServiceNow. It all comes down to your
requirements!

TIP FROM THE FIELD


ServiceNow is always enhancing the pla\orm. For example, the Embedded Help has been
updated and a new feature called Guided Tours has been added. Research these op?ons
before you script a solu?on to guide users. If you have already scripted a solu?on, revisit
your code and see if these new baseline op?ons can replace the script.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 10
The phrase “Modify a baseline script and you own it.” strengthened the copy, deac?vate, change
the copy process. The strategy was validated when the number of skipped files were reduced aVer
an upgrade. The original record, other than changing the value of the Ac?ve field, was s?ll the same
and it was upgraded. Upgraded baseline files and fewer skipped files was seen as a good thing.

Problems with this strategy:


• There are two files, the original and the copy, that need to be maintained. Maintenance doubles
each ?me a customiza?on is made.
• With each release, the customized record becomes older. Customers do not receive the
advancements of a new release. In some cases, a new release may rely on the original record
being updated. Developers may make more changes to compensate for the original record being
inac?ve.

The current beFer choice is:


• Understand that customiza?on can be costly and should be carefully considered.
• Research ServiceNow’s APIs. Can a no code approach do the same thing?.
• Determine If the customiza?on is necessary.
• Modify the baseline record.
• Be ready to review and revert the skipped file, if needed, aVer an upgrade.

Note: Changes made to a record that are only the result of changing the AcEve field are excluded
from update tracking. This allows you to change the field value without affec?ng the Updated and
Updated by system fields.

If you are interested in learning more about Excluding a field from an update, see ServiceNow's
Product documenta?on for addi?onal informa?on.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 11
Baseline, the admin role has access to all pla\orm features, func?ons, and data, regardless of
security constraints. Grant this privilege carefully! If you have sensi?ve informa?on such as private
HR records, ServiceNow recommends gran?ng a custom admin role to administrator who will
maintain that applica?on.

More granular administra?ve roles such as business_rule_admin, client_script_admin,


script_include_admin, ui_policy_admin, grant specific access rights without gran?ng the broader
privileges of the admin role. For example, an administrator can grant a user rights to change UI
Policies, but not the rights to edit Client Scripts.

IMPORTANT
Specific admin roles do not change the access level and behavior of the admin role, which
grants general administra?ve privileges across the pla\orm.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 12
Where a script executes maFers:
• Performance considera?ons.
• Access to objects and methods:
- Client-side scripts have access to data on forms and in lists.
- Server-side scripts have access to database records.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 13
The Syntax Editor is enabled baseline for new instances. For upgraded instances, a System
Administrator must ac?vate the Syntax Editor [com.glide.syntax_editor] plugin.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 14
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 15
Syntax coloring improves the readability of a script.

Comments will help you, future you, coworkers, and the next administrator understand the code.
Comments will not affect the code’s execu?on.

JavaScript commands tell the pla\orm what to do.

When wri?ng scripts, you cannot choose a JavaScript reserved word as a variable name.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 16
Loca?ng matching characters is especially useful for debugging.

TIP FROM THE FIELD


If you do not have a corresponding parentheses, bracket, or quote, you may get
unexpected results. Use the red highlights when you put your cursor next to one of these
characters to help debug an issue. Did a closing character (parentheses, bracket, or quote)
get highlighted when you put your cursor next to an open character? Did the correct open
character highlight when you put the cursor next to the close character?

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 17
While edi?ng a script, Context-SensiEve Help can be invoked by using the following keystrokes at
the cursor loca?on:
• Ctrl + Space (both Mac/Windows)
• . (a period)

Sugges?ons are context-sensi?ve rela?ve to the cursor's current posi?on and are filtered based on
API type. For example, when working on a server-side script, only sugges?ons from server-side APIs
display. When working on a client-side script, only sugges?ons 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.
• Con?nue typing un?l the element becomes highlighted, then press the <Tab> or <Enter> key.
• Double-click an element in the list.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 18
Locally declared objects are only available to the current script.

IMPORTANT
• If the keyboard language is different from the instance language, you may experience
unexpected behavior.
• Context-Sensi?ve Help is disabled for XML fields and UI Ac?ons.
• Sugges?ons provided by Context-Sensi?ve Help are part of the Scoped Applica?on API.
If an element does not appear in the list of sugges?ons, simply con?nue typing the
element’s name. Context-Sensi?ve Help turns off when the text being entered no
longer matches any sugges?ons in the list.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 19
Hover over an icon to see its keyboard shortcut.
Terms and DefiniEons:
Toggle Syntax Editor – enables/disables the Syntax Editor.

Comment Selected Code – comments/uncomments out the selected code.

Format Code – applies the proper indenta?on to the 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.

Replace All – replaces all occurrences of a string in the script.

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 edi?ng.

Help – displays the keyboard shortcuts help screen.

Save – saves changes without leaving the current view.

Check Syntax – checks the code for syntax errors.

Script Debugger – opens the Script Debugger in a new browser.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 20
When the Syntax Editor is off, a Go to line buFon appears in the toolbar. To use the buFon:
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 senng
the glide.ui.javascript_editor property to false.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 21
Well documented code is as important as having your code working!

To uncomment code:
1. Highlight the code to be made ac?ve.
2. Select the Toggle Comment buFon. The forward slashes at the beginning of each line of code
will disappear.

Mul?ple lines of code can also be commented out by enclosing the selected block with the /* and
*/ characters.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 22
The Syntax Editor applies auto-indenta?on to code as it is wriFen. Select the Format Code icon to
re-apply indenta?on if needed.

Keyboard commands can also be used to quickly format your code. (Can be used in all scripEng
fields across the plaGorm.)
1. Ctrl-A/Cmd-A (select all)
2. ShiV-Tab (format code)

Applying standard formanng is another strategy used to improve readability.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 23
To replace a string in the script using the Replace buFon:
1. Select the Replace buFon.
2. Enter the text to replace in the Replace field and press the <Enter> key.
3. Enter the replacement text in the With field and press the <Enter> key.
4. Select Yes to replace, or No to skip for each match. Select Stop to discon?nue the
replacement process.

To replace a string in the script using the Replace All buFon:


1. Select the Replace All buFon.
2. Enter the text to replace in the Replace field and press the <Enter> key.
3. Enter the replacement text in the With field and press the <Enter> key.

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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 24
To find a specific string in the Syntax Editor:
1. Select the Search buFon.
2. Enter the text to search for in the Search field.
3. Press the <Enter> key on the keyboard.

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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 25
Every script has two parts:
1. Trigger (when to execute).
2. Script (what to do).

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 buFon to
maximize the Syntax Editor. Select the buFon again to restore the Syntax Editor to its default size.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 26
For example, in the Syntax Editor, typing the word for followed by pressing the <Tab> key on your
keyboard results in the following inser?on at the cursor's posi?on:

for (var i=0; i< myArray.length; i++) {


//myArray[i];
}

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 27
Navigate to System DefiniEon > Syntax Editor Macros to create new or edit exis?ng Editor Macros.

Name – macro keyword users type to insert the macro text. (Do not use special characters like
period and quotes)
ApplicaEon – iden?fies the scope of the macro.
Comments – provide a descrip?on 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
No?ce the Syntax Editor is not available for the Text field. You are responsible for the
accuracy of your macros.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 28
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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 29
The system automa?cally 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.

All errors must be corrected before a script can be saved.

This feature can be turned off by selec?ng the Toggle Syntax Check icon.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 30
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 31
The Applica?on Navigator provides links to all applica?ons and modules in the ServiceNow pla\orm.
• All applicaEons – all applica?ons and modules are displayed. Double-click the All applicaEons icon for
expand/collapse all func?onality.
• Favorites – only items iden?fied as favorites are displayed. Favorites are configured on a per user basis.
When the star icon to the right of an Applica?on is selected, all the modules under the applica?on are listed
as favorites.
• Your history – list of most recently accessed items. System Administrators can increase/decrease the
number of records pulled by senng the value of the glide.ui.nav.history_length system property. Baseline,
the ini?al number of records is 30.
Select the Minimize/Maximize Navigator buFon to collapse or expand the Applica?on 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 select Create Favorite on the record’s Context menu or by drag the
record from a list to your list of favorites.
• Save a list as a Favorite by selec?ng Create Favorite on the list's Context menu or by dragging a
breadcrumb condi?on 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 aVer the search string alphabe?cally also).
o *mySearchString – does a "contains" search.
o mySearchString% – does a "starts with" search.
o %mySearchString – does an "ends with" search.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 32
Achieve the same result by selec?ng Configure > All from a form's Context Menu, but by using the
command in the Applica?on Navigator’s Search field you do not have to be on that form to get to the
lists of different configura?on records. Another shortcut to save ?me while developing.

Other available Applica?on Navigator commands include:


• <table_name>.list – opens the list view of the table in the content pane.
• <table_name>.LIST – opens the list view of the table in a new window or tab.
• <table_name>.form or <table_name>.do – opens the form view of the table in the content pane.
• <table_name>.FORM – opens the form view of the table in a new window or tab.
• <table_name>.CONFIG – opens the configura?on view of the table in a new window or tab.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 33
Module Labs

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 34
Lab
Using the Syntax Editor 01.01
615-20m

Lab Summary
You will achieve the following:
• In this lab, you will practice using the Syntax Editor in preparation for
writing scripts in ServiceNow.

A. Preparation
1. Navigate to Self-Service > Knowledge on the Application Navigator.

2. Use the Search field to look for Lab Answer Guide.

3. Select the article, the file automatically downloads.

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.

B. Use the Syntax Editor


1. Type Client Script in the Application Navigator's filter
field. TIP FROM
THE FIELD:
2. Select the System Definition > Client Scripts module. Typing the whole
name of a module
every time to open it
can get tiresome.
Identify and type the
unique letters of a
module name in the
filter. Try nt sc. Did
Client Scripts show
up in the menu?

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 35
3. Select the New button ( )

4. Enter Lab 1.1 Using the Syntax Editor in the Name field.

5. De-select the Active checkbox to prevent the script from running.

6. In the Script field, enter the following text:

Code to test the Syntax Editor features


- Syntax coloring
- Special character highlighting
- Layout
- And more!

7. Convert the text to a comment.

a) Select all of the text.

b) Select the Toggle Comment button ( ) on the Syntax Editor


toolbar

8. In the Script field, below the commented lines, enter the following
script exactly as it appears here. As you enter the script, note the
syntax coloring, special character highlighting, auto-indentation and
the automatic creation of closing braces and quotes.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 36
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.

12. Use the Replace feature to change the number 2 in myObj.property2


to myObj.propertyTwo.

a) Select the Replace button ( ).

b) Type 2 in the Replace field then press <enter> on your keyboard.

c) Type Two in the With field then press <enter> on your keyboard.

d) Select No when prompted to replace the 2 in 32.

e) Select Yes when prompted to replace the number 2 in property2


with the word Two.

13. Use the Replace All feature to change the value for myObj.property3 from
Third to third.

a) Select the Replace All button ( ).

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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 37
C. Create a Syntax Editor Macro
1. Navigate to System Definition > Syntax Editor Macros.

2. Create a new macro:


Name: try
Comment: Client-side try/catch
Text:

3. Select Submit.

4. Open the Lab 1.1 Using the Syntax Editor Client TIP FROM
Script. Place the cursor on a new line below the THE FIELD:
existing script.
You can use the
5. Test the 'try/catch' macro by typing try and navigation filter to
pressing the <tab> key on your keyboard. locate the Client
Scripts module.
6. Did the macro display? However, take a look
at the Your history
(If not, confirm the Name is correct in the Syntax tab ( ). Is your
Editor Macro record you created in step-2 and re- Client Script
test.) available? This
provides a direct link
7. Place the cursor on a new line below the existing to the record and
script, type help and press the <tab> key on your saves you some
keyboard. typing.
a) Review the description for the try macro. Where
did the value come from?
____________________________________________________________

b) Review the description for the info macro. Why is it blank?


____________________________________________________________

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 38
8. Syntax errors will prevent a save at this time, comment out or delete
the help macro text.

9. Select Update to save the changes and close the record.

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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 39
Lab
Syntax Checking 01.02
65-10m

Lab Summary
You will achieve the following:
• In this lab, you will practice with the Syntax Checker to determine which
types of errors the checker catches.

A. Syntax Checking in the Script Editor


1. Create a new Client Script.

2. Configure the trigger:

Name: Lab 1.2 Syntax Checking


Active: Not selected (unchecked)

3. Enter this script exactly as shown (including errors):

4. Try to save your script. Did it save?

5. How can you tell?

_____________________________________________________________________

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 40
6. Hover the mouse cursor over the orange ( ) and red ( ) symbols to
the left of the line numbers to read the warning and error messages

7. Hover the mouse over the orange and red underlines in the script to
read the warning and error messages.

8. Correct the warnings and errors until no alerts remain.

9. Did the Syntax Checker find all the errors in the script? Which error(s)
were not found?

_____________________________________________________________________

_____________________________________________________________________

_____________________________________________________________________

10. Select Submit.

Lab Completion
You have practiced Syntax Checking and understand not all errors are caught.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 41
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 42
Baseline applica?ons provided by ServiceNow (e.g. Incident, Service Catalog, Service Portal, etc…),
as well as any custom applica?on built prior to the Fuji release are in the Global scope. It is difficult
to protect/isolate applica?on data in the Global scope.

There is no migra?on path to a custom or different scope.

TIP FROM THE FIELD


Turn on the Show applicaEon picker in header developer senng so you can easily switch
between applica?on scopes using a drop-down on the Header bar.
1. Select the Se\ngs icon located on the right-side of the banner.
2. Select Developer.
3. Select Show applicaEon picker in header.
4. Use the ApplicaEon drop-down list to switch between applica?on scopes.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 43
Ar?facts are the applicaEon files in an applica?on. Examples include, but are not limited to, Tables,
Access Controls, Email No?fica?ons, Data Policies, Client Scripts, Business Rules, Script Includes,
etc…

Applica?on developers specify an applica?on scope when they create a new applica?on. They can
also specify what parts of an applica?on are accessible to other applica?ons from:
• The Custom applica?on record.
• Each applica?on Table record.

For example, suppose you create a Travel & Expanse Management applica?on. By default, the
applica?on can access and change its own tables and business logic, but other applica?ons in the
pla\orm cannot unless you grant them explicit permission to do so.

Applica?on scope ensures:


• The applica?on does not interrupt core business services.
• Other applica?ons do not interfere with its normal func?oning.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 44
The applica?on scope prevents naming conflicts and allows the contextual development
environment to determine what changes, if any, are permiFed.

Applica?ons in the Global scope do not append a unique namespace iden?fier to the applica?on
name.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 45
Built-in limita?ons prevent developers from upda?ng ar?facts while in a different scope. This
protects the applica?on from inadvertent modifica?ons.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 46
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 47
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,
defini?ons on what they do, instruc?ons on how to use them, as well as sample scripts wriFen
by ServiceNow developers.
• Visit ServiceNow's official DocumentaEon site to review API release notes.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 48
API Documenta?on is presented as Scoped or Legacy (Global) documenta?on. Understand what
scope you are using, because you cannot call a global Glide API in a scoped applica?on.

Another thing you want to consider is the version of your instance. Make sure the documenta?on
you are looking at is the version of your instance.

In the API documenta?on, you will find links to scope applica?on, legacy applica?on, and instance
versions within the documenta?on.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 49
ES5 Standards Mode is the default mode when crea?ng new scoped scripts. It supports
ECMAScript5 syntax, extensions, and features, including:
• The 'use strict' declara?on.
• Control over extensibility of objects.
• Get and set proper?es on objects.
• Control over write-ability, configurability, and innumerability of object proper?es.
• New Array and Date methods.
• Na?ve JSON support.
• Support for modern third-party libraries such as lodash.js and moment.js.

CompaEbility Mode supports ECMAScript3 with ServiceNow behaviors and extensions


• All Global scripts.
• All scripts developed prior to the Helsinki release.

Visit hFps://en.wikipedia.org/wiki/ECMAScript if you are interested in learning more about


ECMAScript.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 50
Overview
© 2018 ServiceNow, Inc. All Rights Reserved 51
There are many resources available for working with JavaScript.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 52
Membership in the ServiceNow community is free!

Select LOG IN at the top-right of the page to sign in or create an account.

With an account, you have access to all of these features:


• Post ques?ons on our Forums.
• Comment on our Blogs.
• Rate content.
• Register for Local Events.
• Join Local User Groups.
• Get to know ServiceNow customers, partners, and employees.

IMPORTANT
Get feedback not only from your internal sources, but from other customer sources as
well.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 53
Join a SNUG near you today. AFending an event is a fantas?c opportunity to gain new knowledge
and network with your peers that share a passion for ServiceNow. The benefits of aFending a SNUG
are numerous.
• Face-to-face interac?ons with ServiceNow subject maFer experts, product evangelists,
execu?ves and partners.
• Knowledge transfer across diverse organiza?ons, industries, and ServiceNow use cases.
• Connect with and learn from peers while developing professional rela?onships.
• Insight into upcoming product releases, roadmaps and company updates including sneak
previews into new features and on-going product development.
• Help shape future product direc?on by providing real-?me feedback.
• Access to live customer tes?monials, demos and hands on workshops.
• Open forum to discuss ideas, industry trends, challenges and observa?ons.

SNUGs are managed by ServiceNow users just like you. If there is no SNUG in your area, you can
create one!

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 54
Product Documenta?on provides ServiceNow's official documenta?on about the pla\orm. Use the
Search documentaEon field to quickly navigate to the informa?on you are looking for.

In addi?on to naviga?ng directly to the website, you can also select the Search Product
DocumentaEon link from the Help icon on the banner frame in any instance.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 55
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 collabora?on and sharing.

It is designed to maximize the produc?vity, effec?veness and efficiency of developers crea?ng


value-added applica?ons and solu?ons on ServiceNow.

Register for a personal developer instance to prac?ce building, extending and integra?ng new
applica?ons in a safe sand-box environment.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 56
Learn on your own schedule, at your desired pace.

The ServiceNow Learning Library provides a cost-effec?ve ($1,000 per user/per year) op?on to
supplement our tradi?onal 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 con?nued later – allowing you to learn on a schedule that aligns with your
availability. Mobile-ready content provides access at any ?me and from any loca?on.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 57
Module Labs

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 58
Lab
Explore Scripting Resources 01.03
615-20m

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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 59
4. Join the ServiceNow User Group (SNUG) nearest you.

a) From the Header bar, select Groups > ServiceNow User Groups.

b) Select a Region from the Map.

c) Select a ServiceNow User Group from the list that appears below
the map.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 60
d) Select the Request Access button at the
top-right corner of the page. TIP FROM
THE FIELD:
There are more
regions and groups
than shown here.
Type a country,
state, or major city
followed by the
words user group in
the site’s search box
to find your user
group.

5. Where do you search for existing content in Community?

____________________________________________________________________

6. Search Community for the string Ask Why.

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.

c) Open the article in Chuck Tomasi's Blog.

d) Open and read the article.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 61
7. When you cannot find the information you are looking for in
Community; how do you ask a question?

_____________________________________________________________________

_____________________________________________________________________

B. Explore Documentation
1. Navigate to ServiceNow's official Product Documentation website:
docs.servicenow.com.

2. Select London.

3. Open the London Release Notes and Upgrades article.

4. On the left Navigation menu, expand the Features and changes by


product category, then expand the Now Platform release notes
category. Lastly, open 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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 62
5. Review the article. What information is provided? Record your answer
here:

____________________________________________________________________

____________________________________________________________________

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.

b) Open the Useful scripts article.

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

2. Select API > Server.

3. On the left Navigation menu, select Legacy.

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.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 63
5. Select the GlideDateTime() method.

6. Review the documentation in the middle of the screen.

7. Notice the examples in each section.

8. What Date/Time format does the GlideDateTime object use?

__________________________________________________________________

Lab Completion
Good Job! You have really explored some of the ServiceNow resources that are
at your fingertips when you need help scripting.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 64
Good Prac)ces

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 65
Discuss: Why, when, and how oVen would you use the capabili?es shown in this module.

Overview
© 2018 ServiceNow, Inc. All Rights Reserved 66
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 67
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 68
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 69
Although modern browsers largely interpret JavaScript the same way, you may s:ll observe
browser-dependent behaviors in client-side scripts.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 70
Navigate to the System Defini,on > Client Scripts module to create or modify Client Scripts.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 71
All scripts have a trigger specifying when a script's logic should execute. The trigger configura:on
fields depend on the script type.

The Descrip,on field is for documen:ng the script. Include informa:on like who wrote the script,
what business requirement the script is for and any other per:nent informa:on.

The Messages field is used for interna:onalizing 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 condi:ons in the trigger are met.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 72
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 iden:fy 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.
Applica,on – iden:fies the scope of the Client Script.
Ac,ve – if selected the script is execu:ng in the run:me 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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 73
Order is the sequence in which the Client Scripts are executed, from lowest to highest. By
conven:on, Order numbers contain three digits. For example: 150, 300, or 675.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 74
Users do not have the ability to modify form fields while an onLoad() Client Script executes.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 75
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-manipula:on of the current form or set default
record values.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 76
Users do not have the ability to modify form fields while an onSubmit() Client Script executes.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 77
TIP FROM THE FIELD
Typically, onSubmit() Client Scripts validate data on the form and ensure the submission
makes sense. If the inputs the user submits do not make sense, an onSubmit() Client
Script can cancel form submission by returning a value of false.

function onSubmit() {
if(!myCondition) {
return false;
}
else {
//perform some logic here
}
}

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 78
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
ConfiguraCon 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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 79
An onChange() Client Script runs when a par:cular field value changes on the form.

The onChange() Client Script must specify these parameters:


• control – name of the object (field_name) whose value just changed. The object is iden:fied in
the Field name field on the Client Script form.
• oldValue – value of the control field when the form loaded and prior to the change. For
example, if the value of Assigned to changes from Mab to Miranda the value of the parameter
oldValue is Mab. oldValue will always be Mab (the value when the form loaded) no maber
how many :mes the Assigned to value changes acer the original form load.
• newValue – value of the control field acer the change. For example, if the value of Assigned to
changes from Mab to Miranda, the value of the parameter newValue is Miranda.
• isLoading – boolean value indica:ng whether the change is occurring as part of a form load.
Value is true if change is due to a form load. A form load means all of a form's fields changed.
• isTemplate – boolean value indica:ng whether the change occurred due to popula:on of the
field by a template. Value is true if change is due to popula:on from a template.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 80
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.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {


if (isLoading || newValue === '' || isTemplate) {
return;
}

//Type appropriate comment here, and begin script below


}

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 81
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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 82
Parameters automa:cally passed to an onCellEdit() Client Script:
• sysIDs – sys_id of the edited item(s).
• table – the table name of the edited item(s).
• oldValues – the old value of the edited cell(s).
• newValue – the new value of the edited cell(s). Is the same for all edited items.
• callback – a callback will con:nue the execu:on of other related cell edit scripts.

You must pass back either true or false in the callback func:on. If true is passed as a parameter, the
other scripts are executed or the change is commibed if there are no more scripts. If false is passed
as a parameter, any further scripts are not executed and the change is not commibed.

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

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 83
Module Labs

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 84
Lab
Two Simple Client Scripts 02.01
615-20m

Lab Summary
You will achieve the following:
• In this lab, you will write and test two simple Client Scripts. Consider
saving the Client Scripts module as a Favorite before beginning this
lab.
• The first script creates an onLoad() Client Script that generates an alert.
• The second script creates an onCellEdit() Client Script to stop Incident
records from being set to Resolved or Closed from a list view.

A. Create an onLoad() Client Script


1. Create a new Client Script.

Name: Lab 2.1 onLoad Alert


Table: Incident [incident]
UI Type: Desktop
Type: onLoad
Active: Selected (checked)
Inherited: Not selected (not checked)
Global: Selected (checked)
Description: Lab 2.1 onLoad Client Script

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 85
2. Note the onLoad() function template populates the script field.

Replace the existing comment and add the following alert to the
function.

TIP FROM
3. Select Format Code to re-align the script. (This THE FIELD:
is a good 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?

_________________________________________________________________

2. Is this the behavior you expected? If not, debug and re-test.

3. Select OK.

4. Make a change to any field value.

5. Select Save on the form's Context menu to save the record and remain
on the form.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 86
6. Does the Lab 2.1 onLoad Alert Client Script execute again? Why or why
not? Explain your reasoning:

_________________________________________________________________

7. Create a new Incident. What happens when the form loads for the
new incident? Is this the behavior you expected?

_________________________________________________________________

8. Make the Client Script inactive.

a) Open the Lab 2.1 onLoad Alert Client Script.

b) Uncheck the Active field.

c) Select Update.

C. Create an onCellEdit() Client Script


1. Create a new Client Script.
Name: Lab 2.1 onCellEdit Alert
Table: Incident [incident]
UI Type: Desktop
Type: onCellEdit
Field Name: State
Active: Selected (checked)
Inherited: Not selected (not checked)
Global: Selected (checked)
Description: Lab 2.1 onCellEdit Alert

2. Examine the pseudo-code for the script you will write:

• Create the saveAndClose variable with the value of true


• If the newValue of State is Resolved, alert the user they cannot change
State to Resolved from a list and set the value of the saveAndClose
variable to false
• If the newValue of State is Closed, alert the user they cannot change
State to Closed from a list and set the value of the saveAndClose
variable to false
• Execute the callback function returning the value of saveAndClose
• If true is returned, the new value of the State field is committed
• If false is returned, the new value of the State field is not committed

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 87
3. Write the following script:

4. Select Submit.

D. Test Your Work


1. Navigate to Incident > Open.

2. Without opening a record, pick any Incident in the list. Record the
current value of its State field:

_______________________

3. Update the value of State to


Resolved from the list view.

a) Double-click the State field.

b) Select Resolved from the drop-


down list.

c) Select the green checkmark to


save the change.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 88
4. Did an alert appear advising you cannot change the State to
'Resolved' from a list? If not, debug and re-test your script.

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 purple.)

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.

10. Select OK.

11. Did the Closed value remain in any of the State fields? Why or why
not?

_________________________________________________________________

12. Select OK.

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 Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 89
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 90
ServiceNow provides client-side JavaScript APIs:
g_form – object whose proper:es are methods used to manage form and its fields in the record.
g_user – object whose proper:es contain session informa:on about the currently logged in user
and their role(s).
g_scratchpad – object passed to a Client Script from a server-side script known as a Display Business
Rule. The object’s proper:es and values are determined by the server-side script.

In addi:on 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 metho
ds.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 91
Object proper,es are the fields from the currently loaded record.

Object values are the field values when the record is ini:ally loaded.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 92
GlideForm methods are only used client-side.

Examples:
g_form.addInfoMessage() – displays an informa:onal message at the top of a form.
g_form.addOp,on() – adds an op:on to the end of a Choice list.
g_form.clearMessages() – removes messages previously added to the form.
g_form.clearOp,ons() – removes all op:ons from a Choice list.
g_form.clearValue() – clears a field's value.
g_form.flash() – flashes a field's label to draw aben:on to it.
g_form.getReference() – retrieves a reference object from the database.
g_form.getSec,ons() – returns the elements of a form's sec:on 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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 93
For example, the first parameter required by the addDecora:on() 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');

TIP FROM THE FIELD


Show – ‘field_name’ op:on on the Context menu works great to display the name of a
field. A popup with a few of the field’s proper:es are displayed. Copy the field name for
your script. Addi:onal proper:es include Table, Type, Max Length, and Abributes.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 94
To locate a g_form method manually:
1. Select API > Client.
2. Expand the GlideForm class.
3. Locate and select the method of interest.
• The method's syntax is documented in the middle-column of the page. Most methods
have their parameters and return value documented.
• If an example is included, it is located to the right of the method's documenta:on.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 95
Since JavaScript is weakly typed, it is not always necessary to verify data type when scrip:ng. In the
case of the g_form.getValue() method however, you must pay aben:on 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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 96
Right-click a field's label and select Show – '<field_name>' from the Context menu to confirm a
field's data type.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 97
To see a choice list's values, right-click the field's label and select Show Choice List.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 98
A sys_id is the database's unique key for a record.

TIP FROM THE FIELD


The examples shown have used the alert() method in a Client Script to show the value of a
single field. You can see several field values at once without a Client Script. If you have the
'admin' role, select Show XML on the form’s Context menu. This will display the record’s
data in XML format.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 99
For the form shown, the g_user object contains the following proper:es and values for Beth Anglin:
g_user = {
userName: "beth.anglin",
userID: "46d44a23a9fe19810012d100cca80666",
firstName: "Beth",
lastName: "Anglin"
}

Script used for the alert shown:


function onSubmit() {
if(g_form.isNewRecord()){
alert('Thank you for submitting this Incident ' +
g_user.firstName);
}
}

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 100
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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 101
Module Labs

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 102
Lab
g_form and g_user 2.2
620-25m

Lab Summary
You will achieve the following:
• In this lab, you will 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

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 103
The fields should not be mandatory in the event the information required to
populate them is not known at the time of the initial submission. If this is the
case, details as to why the information is missing should be added to the
'Additional comments' field.

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.

a) Navigate to User Administration > Roles.

b) Select New to create a new Role.


Name: major_inc_mgr
Description: Role required for Major Incident Managers

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.

a) Open User Administration > Groups.

b) Select New to create a new Group.


Name: Major Incident Managers
Description: Major Incident Managers

c) Save the record, remain on the form.

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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 104
B. Use both g_form and g_user methods in a Client Script
1. Create a new Client Script.
Name: Lab 2.2 Confirm Major Incident Details
Table: Incident [incident]
UI Type: Desktop
Type: onSubmit
Active: Selected (checked)
Inherited: Not selected (not checked)
Global: Selected (checked)
Description: Confirm initial P1 details are included if the Incident
creator is not a Major Incident Manager

2. Examine the pseudo-code for the script you will write:

When the form is submitted, saved or updated


• If Impact and Urgency are both high and the user does not have
the major_inc_mgr role
• Create the ans variable to store the user's response to a
confirmation box asking them to ensure base information is
included in the record before submitting a Priority-1 incident
• If the user cancels the submission
o Generate an alert stating the incident was not submitted and
provide instructions to use the Additional comments field if Major
Incident base information is missing
o Add a field messages below the Category, Configuration item,
Assignment group and Short description fields identifying them as
Major Incident base fields
• Return true or false based on the confirmation box response

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 105
3. Write the following script:

4. Select Submit.

C. Test Your Work


1. Create a new Incident, populate the mandatory fields, and set both
the Impact and Urgency values to 1-High.

2. Save the record, remain on the form.

3. When the confirmation window opens, cancel the submission.

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

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 106
7. Impersonate a user and create a major Incident.

a) Select the System Administrator avatar on


the Header bar’s top-right corner to display TIP FROM
the Logged-in User's Context menu. THE FIELD:
As an administrator,
b) Select Impersonate User. you will use
impersonate quite
often. The shortcut to
open impersonate is
control + option + i
on Mac and Ctrl +
Alt + i on Windows.

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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 107
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 Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 108
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 109
In some cases, more than one debugging strategy may need to be used.

The built-in and JavaScript debugging tools will be reviewed.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 110
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 mul:ple administrator/developer
environment this approach has the poten:al 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 iden:fy 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 combina:on 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'));
}

TIP FROM THE FIELD


Create a Debug Syntax Editor Macro to quickly insert commonly used debugging code.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 111
Follow these steps to open the JavaScript Log (admin users only):
1. Select the System SeZngs (gear) icon on the Header bar.
2. Turn the JavaScript Log and Field Watcher bubon on. The JavaScript Log opens at the bobom of the page (Small,
Medium, and Large buNons allow you to select your preferred window size).
3. Create the condi:ons 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 bubon on the System Senngs 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 opera:ng systems.

Any argument passed to the jslog() method appears in the JavaScript Debug window. Such as:
• Strings
• g_form or g_user proper:es or methods
• Variables
• JavaScript string escape characters such as "\n" (new line) and "\t" (tab).

TIP FROM THE FIELD


Prepend your jslog() messages with an easily iden:fiable string such as the script name or your ini:als so you
can quickly search through the debug messages. In this example, the string "LOG MSG!!" is used.
jslog("LOG MSG!! The value of Priority is: " +
g_form.getValue('priority'));

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 112
Use this strategy to look for Client Script issues causing long load :mes.

Administrators can disable the Response Time Indicator by senng the glide.ui.response_Cme
property to false.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 113
Try/Catch syntax:
try{
//code to execute goes here
}
catch(err){
//code to deal with error here
}

err is a JavaScript object with proper:es descrip:on, message, name, and number.

You can throw your own error messages for the catch func:on using the JavaScript throw()
func:on. Try/catch only traps run:me errors. Using throw() you can also catch user errors such as
entering an invalid data value in a field.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 114
Module Labs

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 115
Lab
Debugging Client Scripts 02.03
620-25m

Lab Summary
You will achieve the following:
• In this lab, you will practice debugging 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.

2. Select the Active checkbox to make the script active.

3. Examine the pseudo-code for the script:


• When the value of Impact changes
• Store the current value of State in the variable incState
o If the value of incState is 1
§ Add a decoration to the State field
§ Have the State label flash the color teal
o If Impact has the value High or Medium
§ Remove the State choice list options On Hold, Resolved,
Closed, and Canceled
§ Log a message to the top of the form confirming the State
options removal
o Else if the form is not loading and Impact does not have the
value High or Medium
§ Clear the State choice list
§ Add options back to the State choice list
§ Set the State field to the value of incState

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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 116
B. Observe the Current Execution of the Script
1. Create a new Incident.

2. Without changing the value of the State field, open the drop-down
choice list and make a mental note of the available options.

3. Update the value of Impact to 1-High.

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

C. Use jslog() to confirm Variable Values and Script


Execution
1. Open the Lab 2.3 Client Script Debugging Client Script.

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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 117
D. Turn on the JavaScript Log and Field Watcher
1. Select the System Settings (gear) icon on the right-side of the Header
bar.

2. Select Developer.

3. Turn the JavaScript Log and Field Watcher switch on.

4. Close the System Settings window when you are ready to proceed.

E. Force the Updated Script to Execute


1. Create a new Incident.

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.

4. Update the value of Impact to 1-High.

5. Review the log messages in the JavaScript Log.


• What is the value currently in the incState variable? ______
• What should it be? ______
• Does the string "LINE 11 EXECUTED!" appear as a logged message?
_______

6. What can you conclude regarding the debugging output currently in


the JavaScript Log?

____________________________________________________________________

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 118
7. At this point, you know something is wrong with the value in incState
variable. Before leaving the Incident form, double-check the State
field's name by right-clicking the field's label. What is the exact spelling
of the State field's name? ______________

8. Open the Lab 2.3 Client Script Debugging Client Script.

9. Locate the statement at the beginning of your script that reads:

var incState = g_form.getValue('incident');

Review the State field's name in this statement, does it match the field
name you documented in step-7? _________

10. Update the statement to

var incState = g_form.getValue('state');

11. Select Update.

12. Force your updated script to execute by creating a new Incident. If


you closed the JavaScript Log, re-open it.

13. Clear the JavaScript log.

14. Update the value of Impact to 1-High.

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

16. Review the messages in the JavaScript Log.


• Is the value of incState 1? __________
• Does the string "LINE 11 EXECUTED!" appear as a logged message?
_________

17. If you answered No to any of these questions in steps 15 or 16, debug


and re-test.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 119
18. Close the JavaScript Log and Field Watcher by select the Close ( )
icon.

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?

____________________________________________________________________

F. Explore Built-in Debugging Messages


1. Open another Incident where the value of Impact is 1-High or 2-
Medium.

2. Update the value of Impact to 3-Low.

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.

G. Explore Debugging While Impersonating


1. Impersonate Beth Anglin.

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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 120
4. Can Fred turn the JavaScript Log and Field Watcher on? Why or why
not?

____________________________________________________________________

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.

7. Open the Lab 2.3 Client Script Debugging Client Script.


• Remove any debugging statements.
• Make the Client Script inactive.

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 Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 121
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 122
Supported devices for the mobile app
• Apple iPhones running iOS 9 and above.
• Apple iPod touches running iOS 9 and above.
• Apple iPads running iOS 9 and above.
• Android mobile devices running KitKat (4.4) and above.

Requires the Geneva version of a ServiceNow instance or later.

Android and iOS mobile apps are similar with a few minor differences to make experiences unique
to each plasorm. E.g. the loca:on of the Naviga:on menu varies between the two plasorms to stay
consistent with the plasorm-specific UI.

Users without an iOS or Android device can s:ll access an instance on a smartphone by naviga:ng
to the standard URL of an instance in a web browser.

IMPORTANT
Some features are not supported in the Mobile app UI. Always check ServiceNow's Product
documenta:on (docs.servicenow.com) for the most up to date informa:on on which f
eatures have limited to no mobile support.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 123
Steps to create a new Mobile Applica:on menu:
1. Navigate to System Mobile UI > Navigator Apps.
2. Select New.
3. Configure the Mobile Applica:on menu.
4. Select Submit.

Steps to create a Mobile Module from an exis:ng desktop Module:


1. Navigate to System Defini,ons > Modules.
2. Locate and open the desktop Module you want to copy.
3. Select the New Mobile Module Related Link.
4. If required, make any adjustments to the new Mobile Module's default configura:on (e.g.
Order, Roles).
5. Select Submit.

A Mobile Applica:on menu will not appear on the Mobile Navigator un:l at least one Mobile
Module has been added to it. If the Mobile Module is created first, the Mobile Applica:on menu
record is automa:cally created. Review the record if this occurs as the default configura:on may
need adjus:ng (e.g. Order, Roles).

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 124
The UI Type of a Client Script must be set to Mobile / Service Portal or All for the script to run in a
Service Portal environment.

The Service Portal product was developed with a 'Mobile first' approach. One of its best features is
speed; and it achieves its fast response :me because all of the plasorm's desktop components are
not loaded in the Portal environment.

So where it might be temp:ng to set the UI Type of every Client-side script to Mobile/Service Portal
or All, that would defeat the purpose as every Client Script would then load in the Portal
environment. Keep this in mind when you are developing scripts, ask yourself… "Where will this
script execute?" If the answer is "not on a Service Portal page" or "in the ServiceNow app", the
script's UI Type can just be set to Desktop.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 125
g_form.addDecora,on() – add a decora:on next to a field.
g_form.getLabel() – gets a field's label text.
g_form.hasField() – returns true if a field exists on a form.
g_form.removeDecora,on() – removes a decora:on from a field.
g_form.setLabel() – sets a field's label text.

IMPORTANT
Using mobile only g_form methods on the Desktop causes run:me errors. Check the
ServiceNow Developer site for the most current informa:on on mobile g_form methods.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 126
This list was gathered by searching for the string "not available mobile" on the
developer.servicenow.com site. These methods are not deprecated, but are only available for use in
desktop Client Scripts.

IMPORTANT
If these methods are used in Mobile Client Scripts, no ac:on is taken as the mobile
plasorm ignores unsupported methods.

Search ServiceNow's Product documenta:on (docs.servicenow.com) for the ar:cle :tled Mobile
pla^orm migra,on impacts for more informa:on on Mobile Client Script requirements.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 127
To return to the Desktop mode:
1. Open the Applica:on Navigator and select the Home.
2. Select the Profile link on the right-side of the header bar.
3. Select Log Out or Switch to Desktop.

IMPORTANT
Although using the Mobile UI emulator gives you an idea of the mobile experience, it is
always recommended to test using the na:ve mobile app on a mobile devices to
experience the socware the same way your users will.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 128
The JavaScript log and Field Watcher tools are Desktop only tools. To debug Mobile Client Scripts,
use g_form methods and JavaScript alerts.
The g_form methods and alert arguments can be:
• Strings
• g_form proper:es or methods
• g_user proper:es or methods
• Variables
• JavaScript string escape characters such as \n (new line) (ignored for g_form methods)
Remember to remove debugging messages when a script is ready for test and produc:on!
Script used to produce the debugging message in this example:

function onLoad() {
g_form.addInfoMessage("The value of Caller is: " +
g_form.getValue('caller_id'));

try {
g_form.getVal('priority');
}

catch(err) {
g_form.addErrorMessage("A runtime error occurred: " + err);
}
}

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 129
Module Labs

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 130
Lab
Client Scripting for Mobile 02.04
615-20m

Lab Summary
You will achieve the following:
• In this lab, you will practice writing, testing, and debugging a Client Script
for the Mobile platform. When this lab is completed, you will be able to
mark a Cloud Dimensions' Phase II requirement complete.

Business Problem

IT analysts want the ability to submit new Problem records using their mobile
devices.

Project Requirement
Include a Problem > Create New item on the mobile view of the
Application Navigator.

If the user is creating a new Problem and has the 'itil' role:

• Pre-populate the Assigned to field with the name of the logged in


user.
• Have the field label flash red at least 4 times to advise the user they
are the default assignee.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 131
A. Preparation
1. Open Beth Anglin's user record and set her password. Record the new
password here:

_________________________________________________________________

2. Add the Problem application to the Mobile Navigator.

a) Navigate to System Mobile UI > Navigator Apps.

b) Select New.

c) Configure the form:


Name: Problem
Order: 400
Active: Selected (checked)
Roles: itil

d) Select Submit.

3. Create a Create New Mobile Module from an existing desktop Module.

a) Navigate to System Definition > Modules.

b) Locate and open the Problem table's Create New module.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 132
c) Select the New Mobile Module Related Link.

d) Select Submit.

B. Client Scripting for Mobile


1. Create a new Client Script.
Name: Lab 2.4 Client Scripting for Mobile
Table: Problem [problem]
UI Type: All
Type: onLoad
Active: Selected (checked)
Inherited: Not selected (not checked)
Global: Selected (checked)

2. Examine the pseudo-code for the script you will write:


• When the form is loaded
o If the record is new
§ Set the value of the Assigned to field to the logged in user
§ Have the Assigned to label flash the color red

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 133
3. Write the Script:

4. Select Submit.

C. Test the Client Script on the Desktop


1. Impersonate Beth Anglin.

2. Create a new Problem.

3. Did the Assigned to field populate with Beth's name? If not, debug and
re-test.

4. Did the Assigned to label flash? If not, debug and re-tes

D. Test the Client Script in the Mobile Application

1. Download the ServiceNow app from your favorite app store. (For
iPhone devices running iOS9 or above or for Android phones running
KitKat and above).

Note: If unable to download, use the Mobile UI emulator to test (/$m.do).

2. Once installed, open the app and add your class instance. (Skip this
step if you are using the Mobile UI emulator.)

3. Test the Client Script in the ServiceNow app.

a) Login as Beth Anglin.

b) Create a new Problem.

c) Did the Assigned to field populate with Beth's name? If not, debug
and re-test.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 134
d) Did the Assigned to label flash? Why or Why not?

Hint: Look up the flash() method on developer.servicenow.com

_______________________________________________________________

4. Suggest a method that works on the mobile platform to draw the user's
attention to the Assigned to field instead of flash(). Record your answer
here:

____________________________________________________________________

5. Close the Problem record you created in step-3.

6. Return to your desktop. (If you used the Mobile UI emulator, select
Beth’s avatar on the Header bar, select Switch to Desktop, then end
the impersonation.)

7. Open the Lab 2.4 Client Scripting for Mobile Client Script for editing.

8. Replace the g_form.flash('assigned_to','tomato',-8); statement


in the Script field with a statement using the method you suggested in
step 4.

9. Test the changes to the script.

10. Did the method you suggested draw attention to the Assigned to field?
If not, try another method. Continue until you are satisfied.

11. Make the Lab 2.4 Client Scripting for Mobile Client Script inactive.

Lab Verification
Well done! You successfully practiced writing Client Scripts for mobile devices.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 135
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 136
When wri:ng 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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 137
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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 138
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 func:on logic executes when the object returns from the server.

The g_form.getReference() method runs asynchronously when a callback func:on is used. When the
record is returned to the calling script, the logic in the callback func:on executes. If the callback
func:on is omibed, the g_form.getReference() method runs synchronously.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 139
In the example shown, the callerInfo() func:on is called only acer the caller_id record is returned
from the server.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 140
Synchronous getReference() method calls lock the form un:l the requested record is returned from
the database. Asynchronous execu:on allows users to con:nue using the form while the method
call executes.

The first example executes synchronously resul:ng in a poor user experience. getReference()
without a callback func:on will not run on the Mobile plasorm.

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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 141
Module Labs

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 142
Lab
Client Scripting with Reference 02.05
Objects 615-20m

Lab Summary
You will achieve the following:
• In this lab, you will 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.

A. Client Scripting with Reference Objects


1. Create a new Client Script.
Name: Lab 2.5 Reference Objects
Table: Change Request
UI Type: Desktop
Type: onChange
Field: Configuration Item
Active: Selected (checked)
Inherited: Not selected (not checked)
Global: Selected (checked)

2. Examine the pseudo-code for the script you will write:


• When the Configuration Item field on a Change Request is
changed
o Request the CI record from the server and execute the
callback function.
o In the callback function
§ If the CI is '3D Pinball'
• Set the Priority to Low, Risk to None, and Impact to Low.
• Make the Priority, Risk, and Impact fields read-only.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 143
3. Write the script:

4. Select Submit.

B. Test Your Work


1. Create a new Normal Change Request.

2. Enter 3D Pinball in the Configuration Item field.

3. Are the Priority, Risk, and Impact fields set correctly? Are they read-
only? If not, debug and re-test.

4. Change the Configuration Item to anything except 3D Pinball.

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

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 144
7. Select Update.

8. Test and if required, debug.

C. Make a Second getReference() Call in the Same Script


1. Modify the script to display the Requested by user's email address in
the Description field by using a second getReference() method call
and callback function. (Script is on the next page.)

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 145
2. Save the script.

3. Test and if required, debug.

4. Make the Lab 2.5 Reference Objects script inactive.

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 Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 146
Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 147
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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 148
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.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 149
The Compare to Current page is customizable.

Select the Revert to Selected Version bubon at the top of the form to overwrite the Current
Version record with the Selected Version record.

Select the Save Merge bubon to save changes made to the Current Version while on the Compare
to Current page.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 150
You can easily undo recent changes to a script by selec:ng the Revert to this version Related Link to
revert to a previous version.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 151
Lab 2.2 fulfills requirement 1.
Lab 2.4 fulfills requirement 9.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 152
Addi:onal resources for Client Script Best Prac:ces:

• Search for the Client script best prac,ces ar:cle on docs.servicenow.com.

• Search for the Six ways to Improve the Performance of Client


Scrips blog ar:cle on community.servicenow.com.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 153
Discuss: Why, when, and how ocen would you use the capabili:es shown in this module.

Client Scripts
© 2018 ServiceNow, Inc. All Rights Reserved 154
UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 155
In this module you will write, test, and debug UI Policies.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 156
In the basic case UI Policies do not require scrip;ng. In the example shown, no scrip;ng was
required to:
• Make the Number field read-only.
• Make the Configura;on 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 ;mes and easier maintenance.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 157
Navigate to the System UI > UI Policies module to create or modify UI Policies.

UI Policies do not run unless their condi;on is met. In some cases, UI Policies do not have a
condi;on – these UI Policies execute every 4me a form loads and/or is changed.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 158
UI Policy scripts execute client-side.

This example occurs when the baseline Comments mandatory on rejec/on UI Policy executes.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 159
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.
Applica4on – iden;fies the scope of the UI Policy.
Ac4ve – select the checkbox to make the UI Policy ac;ve.
Short descrip4on – supply a short explana;on of what the UI Policy is for. The value in this
field appears in the debugging informa;on.
Order – the sequence in which UI policies are applied, from lowest to highest. Use when
there are mul;ple UI Policies for the same table that may contain conflic;ng logic.
2. Configure the the When to Apply condi;ons (when the UI Policy will run).
3. Save (not Submit) the record.
4. Configure the UI Policy Ac4ons (what the UI Policy will do):
Field name - field for which the UI Policy applies an ac;on.
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 Ac4on does need to be present on the form. For
UI11, ensure any field called by a UI Policy exists on the form.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 160
The Condi4on Builder is not unique to UI Policies; the feature is used across the plaXorm.
Global – the UI Policy applies to all form views if selected.
View – name of the specific form view to which the UI Policies applies. Visible when the Global field
is not selected. If the Global field is not selected and the View field is le[ blank, the script applies
the default view.
Reverse if false – UI Policy ac;ons are reversed and the Execute if false script executed when its UI
Policy condi;ons evaluate to false.
On load – execute on form load and form change.
Inherit – apply this script to any extended tables when selected.

IMPORTANT
Condi;ons 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.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 161
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 Condi;on tests true.
Execute if false – JavaScript executes when the UI Policy Condi;on tests false.

The onCondi/on() func;on in the appropriate UI Policy script fields is automa;cally called when the
condi;on 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.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 162
ServiceNow client-side global variables:
g_form – object whose proper;es are methods used to manage form and its fields in the record.
g_user – object whose proper;es contain session informa;on about the currently logged in user
and their role(s).
g_scratchpad – object passed to a UI Policy from a server-side script known as a Display Business
Rule. The object’s proper;es and values are determined by the server-side script.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 163
All of the Client Script debugging strategies reviewed in the previous module also work for UI
Policies. In addi;on, UI Policies have the Debug UI Policies op;on. This is the only debugging
strategy for seeing the evalua;on of a UI Policy's Condi;on.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 164
Module Labs

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 165
Lab
Incident Resolved / Closed UI 03.01
Policy 620-25m

Lab Summary
You will achieve the following:
• In this lab, you will write, test, and debug a UI Policy. When an
Incident's State is set to Resolved.
• The Urgency and Impact fields are read-only.
• The Resolved by field is mandatory.
• An Info Message advises the user which fields are mandatory before
saving a record.
• When this lab is done, you will be able to mark a Cloud Dimensions'
Phase II requirement 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.

2. In addition to the baseline mandatory fields when a record is put in a


Resolved or Closed state, the Incident Management team would also
like to consistently capture who is resolving Incidents for reporting
purposes.

3. IT Analysts do not always remember to populate the Closure


Information fields as they are on a different tab, and are frustrated with
the amount of times they are presented with the 'Mandatory fields
were missed' alert after they attempt to save the record. They have
requested a message on the form, reminding them which fields are
mandatory before they attempt to save the record.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 166
Project Requirement
Because every requirement is based on the same Incident condition, only one
UI Policy is required to solve all of the business problems. When an Incident’s
state is Resolved or Closed:
• Make the Impact and Urgency fields read-only.
• Make the Closed by field mandatory.
• Configure an Info Message reminding users which fields are mandatory
before they attempt to save a record.

A. Create a UI Policy
1. Navigate to System UI > UI Policies.

2. Create a new UI Policy.


Table: Incident [incident]
Active: Selected (checked)
Short Description: Lab 3.1 Incident Resolved or Closed
Order: 100
Condition: State | is one of | Resolved + Closed
(Hold the 'Shift' key down to select both items in the list)
Global: Selected (checked)
On load: Not selected (not checked)
Reverse if false: Selected (checked)
Inherit: Not selected (not checked)

3. Save the record, remain on the form.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 167
4. Add a UI Policy Action.

a) Scroll down to the UI Policy Actions Related List and select the New
button.

b) Configure the UI Policy Action:

Field name: Urgency


Mandatory: Leave alone
Visible: Leave alone
Read Only: True

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.

i) Save the record, remain on the form.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 168
j) Notice the red dot to the left of the urgency UI Policy Action is no
longer visible.

5. Add two additional UI Policy Actions:

Impact: Read only


Closed by: Mandatory

6. Select (check) the Run scripts field on the Script tab.

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.

8. Write the Execute if true script:

9. Select Update.

B. Test Your Work


1. Open an existing Incident.

2. Set the value of State to Resolved or Closed.

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?

5. Open the Lab 3.1 Incident Resolved or Closed UI Policy.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 169
6. Write the Execute if false script:

7. Select Update.

8. Open an existing Incident.

9. Set the value of the State field to Resolved or Closed.

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?

_____________________________________________________________________

_____________________________________________________________________

C. Practice Debugging a UI Policy


1. Select System Diagnostics > Session Debug > Debug UI Policies to
enable UI Policy debugging.

2. Open the JavaScript Log and Field Watcher pane.

3. Open an existing Incident.

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.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 170
7. Examine the debugging information for the evaluation of the condition
of this lab's UI Policy. What did the condition evaluate to?

____________________

8. Are the correct fields read-only or mandatory?

____________________

9. Select the Clear log button ( ) to remove any messages from the
JavaScript Log.

10. Set the value of State to In Progress.

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?

____________________

14. Close the JavaScript Log and Field Watcher pane.

15. Disable UI Policy Debugging by selecting System Diagnostics > Session


Debug > Disable UI Policies Debug on the Application Navigator.

D. Make the UI Policy Script Mobile


1. Configure the Mobile view of the Incident form to display the Impact,
Urgency, Resolved by, Resolution code, and Resolution notes fields.

a) Open an Incident record.

b) Select Configure > Form Design on the record's Context menu. The
Form Designer opens in a new browser window.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 171
c) Select the Mobile view.

d) Add the Impact, Urgency, Resolved by, Resolution code, and


Resolution notes fields to the form.

e) Select Save.

f) Close the browser tab displaying the Form Designer.

2. Test the UI Policy in the mobile application.

3. The Info Message does not appear on the mobile device. How come?
Record your answer here:

_____________________________________________________________________

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 172
4. Return to your desktop. Open the Lab 3.1 Incident Resolved/Closed UI
Policy for editing.

5. Set the value of the Run scripts in UI type field to All.

6. Select Update.

7. Test the UI Policy in the mobile application again.

8. Did the Info Message appear and disappear when you changed the
value to State? If not, debug and re-test.

9. Make the Lab 3.1 Incident Resolved/Closed UI Policy inactive.

Lab Completion
Great job! You successfully created a UI Policy that works everywhere in the
platform.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 173
Lab 3.1 fulfills requirement 2.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 174
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
applica;on needs.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 175
UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 176
Discuss: Why, when, and how o[en would you use the capabili;es shown in this module.

UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 177
© 2018 ServiceNow, Inc. All Rights Reserved 178
Catalog Scripts and Catalog UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 179
Catalog Scripts and Catalog UI Policies
© 2018 ServiceNow, Inc. All Rights Reserved 180
Catalog client scripts provide form valida3on and dynamic effects. This control of the form makes
the catalog reac3ve 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).

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 181
Navigate to the Service Catalog > Catalog Administra5on > Catalog Client Scripts module to create
or modify Catalog Client Scripts.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 182
Name: Unique name for the Catalog Client Script.
Applies to: Select the item type this Catalog Client Script applies to (A Catalog Item or A Variable
Set).
Ac5ve: Select the check box to enable the Catalog Client Script. Clear the check box to disable the
script.
UI Type: Iden3fy where the Catalog Client Script executes (Desktop, Mobile/Service Portal, or All).
Applica5on: Iden3fies the scope of the Catalog Client Script.
Type: Iden3fy when the Catalog Client Script executes (onChange, onLoad, or onSubmit).
Catalog item or Variable set: Select a Catalog Item or Variable Set from the list.
Variable name: Iden3fy which field to watch for changes, when onChange is selected as the Type.
Applies on a Catalog Item view: Select the check box to apply the Catalog Client Script to Catalog
Items displayed within the order screen on the Service Catalog. Available in the Requester view.
Applies on Requested Items: Select the check box to apply the Catalog Client Script on a Requested
Item form, aOer the item is requested. Available in the Fulfiller view.
Applies on Catalog Tasks: Select the check box to apply the Catalog Client Script when a Catalog
Task form for the item is being displayed. Available in the Fulfiller view.
Applies on the Target Record: Select the check box to support the Catalog UI Policy on a record
created for task-extended tables via Record Producers.
Script: Script what needs to happen when the condi3ons in the trigger are met.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 183
Variables in a Catalog UI Policy condi3on must be visible (even if it is hidden by another UI policy or
read-only) on the form for the condi3on 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 condi3on execute every 3me a form loads and/or is changed.

Limited UI Policy func3onality applies to following variables:


• The Mandatory and Read only policies do not apply to the following variable types: Break,
Container Split, Container End, UI Macro, UI Macro with Label, Label, UI Page.
• The Visible policy does not apply to the following variable types: Break, Container Split,
Container End.

IMPORTANT
Not all Catalog UI Polices require scrip3ng!

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 184
Navigate to the Service Catalog > Catalog Administra5on > Catalog UI Policies module to create or
modify Catalog UI Policies.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 185
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 descrip5on: Enter a brief descrip3on of the Catalog UI Policy. Use this field as a pseudo name.
Applica5on: Iden3fies the scope of the Catalog UI Policy.
Ac5ve: 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 mul3ple policies
for the same table contain conflic3ng logic. Configure the form to display the exis3ng field.
When to Apply
Catalog Condi5ons: Use the Condi3on builder to configure simple condi3ons for the policy using
Catalog Item variables. The policy is applied if the condi3ons 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 CondiCons evaluate to false.
Script
Run scripts: Select the check box to script complex condi3ons and ac3ons.
Run scripts in UI Type: Iden3fy where policy executes (Desktop, Mobile/Service Portal, or All).
Execute if true: Script to execute when the Catalog CondiCons evaluate to true. If Catalog
CondiCons leO blank, script in this field always executes. Use to script complex condi3ons.
Execute if false: Script to execute when the Catalog CondiCons evaluate to false.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 186
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 ar3cle on docs.servicenow.com for more informa3on on
Variable Sets.

IMPORTANT
Applying Catalog UI Policy Ac3ons on a Variable Set is NOT supported on Service Portal.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 187
If a Variable Set behaves the same each 3me 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 3me it is used, manage its behavior with a Catalog Client
Script or Catalog UI Policy at the Catalog Item level.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 188
ServiceNow client-side global variables:
g_form – object whose proper3es are methods used to manage form and its fields in the record.
g_user – object whose proper3es contain session informa3on about the currently logged in user
and their role(s).

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 189
You can also use the Applica3on Navigator to locate the Catalog Client Script and Catalog UI Policies
modules. You can save the modules as favorites too!

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 190
Module Labs

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 191
Lab
Control Variable Choices 04.01
Catalog Client Script 615-20m

Lab Summary
You will achieve the following:
• In this lab, you will 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.

2. Use the Search field to look for Toner.

3. Select the Toner.png article. The file automatically downloads to your


computer.

B. Create a New Catalog Item


1. Navigate to Service Catalog > Catalog Definitions > Maintain Items.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 192
2. Create a new Catalog Item.
Name: Brother Network-Ready Printer Toner
Catalogs: Service Catalog
Category: Printers
Workflow: Service Catalog Item Request
Short Description: Brother TN 2000 Series Toner
Description: Yields approximately 1200 pages
Picture: Toner.png (downloaded earlier in the lab)

3. Save the record, remain on the form.


TIP FROM
C. Create a Variable to Contain the THE FIELD:
The Question is
Available Cartridge Types actually a label for
the variable. In a
1. Select New on the Variables Related List.
Catalog Client Script,
Type: Select Box the Name is used to
Order: 100 reference the
Question variable. Since the
Question: Which pack type would you like to Question will not be
order? in the script, the
Name: pack_type Name should be a
good description of
Type Specification the variable and
Include none: Selected (checked) unique.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 193
2. Save the record, remain on the form.

3. Select New on the Question Choices Related List.


Price: 60.00
Order: 100
Text: Black Cartridge – Single
Value: black1

4. Select Submit.

5. Repeat steps 4-6 to add these additional Question Choices.


Price Order Text Value
260.00 200 Black Cartridges – 5 Pack black5
150.00 300 CYM Cartridges – 3 Pack (1 of each color) cym3
250.00 400 CYM Cartridges – 6 Pack (2 of each color) cym6

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.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 194
7. Select Update

8. Select Try It on the Brother Network-Ready Printer Toner Catalog Item's


Header bar.

9. Verify the price information in the shopping cart changes as expected.

D. Create a Catalog Client Script to Control the Display of


Choices Based on Role
Now that the Catalog Item is in place, you can create the script to remove the
choices as described in the lab goal.

1. On the Brother Network-Ready Printer Toner Catalog Item form, scroll


down to the Catalog Client Scripts Related List and select New.

2. Configure the record.


Name: Toner Choices by Role
Type: onLoad

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.

3. Save the record, remain on the form.

4. Examine the pseudo-code for the script you will write.


• If the logged-in user does not have the itil_admin role
o Hide the CYM Cartridges – 3 Pack (1 of each color) [cym3]
option
o Hide the CYM Cartridges – 6 Pack (2 of each color) [cym6]
option

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 195
5. Write the script.

6. Select Update.

E. Test Your Work


The System Administrator does not have the 'itil_admin' role, therefore you do
not have to impersonate anyone to confirm users without this role can only
order black printer cartridges.

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.

3. Impersonating Bow Ruggeri (this user has the 'itil_admin' role).

4. Navigate to Self-Service > Service Catalog.

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.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 196
6. Select the Brother Network-Ready Printer Toner name to open the
Catalog Item.

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.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 197
Lab
Control Out of State Shipping 04.02
Catalog UI Policy 620-25m

Lab Summary
You will achieve the following:
• In this lab, you will practice using a Catalog UI Policy to easily
configure the display of specific location fields. Then you will script
more complex actions.
• When regular users order a 'Brother Network-Ready Printer
Cartridge', they are only provided a list of California locations as
delivery options. 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.

A. Prerequisite
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.

B. Create a Variable to Confirm a California Delivery


1. Navigate to Service Catalog > Catalog Definitions > Maintain Items.

2. Locate and open the Brother Network-Ready Printer Toner Catalog


Item.

3. Select New on the Variables Related List.


Question
Type: Select Box
Order: 200
Question: California delivery?
Name: ca_location
Default Value
Default value: yes

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 198
4. Save the record, remain on the form
TIP FROM
5. Select New on the Question Choices Related List. THE FIELD:
Notice the Text is
Order: 100 mixed case and the
Text: Yes Value is lowercase.
Value: yes Text (like a field
label) is just for
6. Select Submit. display. The Value
should adhere to the
7. Repeat steps 5-6 to add a NO Question Choice as rules of the language
well. you are writing for. It
is a good habit to be
Order: 200 consistent with
Text: No Values, so use
Value: no lowercase when
possible.
C. Create Two Variables to Provide Location
Selections
1. On the Brother Network-Ready Printer Toner Catalog Item form, select
New on the Variables Related List.

2. Create a California locations only reference field.


Type: Reference
Order: 300

Question
Question: Select a California location for delivery
Name: location_ca

Type Specifications tab


Reference: Location [cmn_location]
Reference qualifier condition: State/Province | contains | CA

3. Select Submit.

4. Select New on the Variables Related List again.

5. Create a non-California locations reference field.


Type: Reference
Order: 400

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 199
Question
Question: Select a location outside of California for delivery
Name: location_other

Type Specifications tab


Reference: Location [cmn_location]
Reference qualifier condition: State/Province | does not contain
| CA

6. Select Submit.

7. Compare your Brother Network-Ready Printer Toner Variable records


with the image below, make any adjustments if necessary.

D. Restrict the Alternate Location Selections to Users With


the 'itil_admin' Role
1. On the Brother Network-Ready Printer Toner Catalog Item form, open
the Toner Choices by Role Catalog Client Script you created in Lab 4.1.

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.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 200
E. Use a Catalog UI Policy to Display the Correct Location
Fields
Since the Catalog Client Script is already controlling who can view the
California delivery [ca_location] and Select a location outside of California for
delivery [location_other] fields, only one Catalog UI Policy is needed to display
the correct Location field to the users who can see the fields, as well as script
the display of a user-friendly Field messages.

1. From the Brother Network-Ready Printer Toner Catalog Item form,


select New on the Catalog UI Policies Related List.

Short description: Display Location Options


Catalog Conditions: ca_location | is | No

2. Save the record, remain on the form.

3. Select New on the Catalog UI Policy Actions Related List.

Variable name: location_ca


Visible: False

4. Select Submit.

5. Add one more Catalog UI Policy Action.

Variable name: location_other


Visible: True

6. Compare your Catalog UI Policy Actions with the image below, make
any adjustments if necessary.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 201
F. Inform Users Additional Shipping Fees Outside of
California Apply
1. Select the Script tab on the Display Location Options Catalog UI Policy
form.

2. Select (check) the Run scripts field.

3. Examine the pseudo-code for the scripts you will write:

• If the item is not being delivered to a California location


o Add a field message below the 'Select a Location' field advising
the user additional shipping fees apply to out of State deliveries
• If the item is being delivered to a California location
o Ensure no field messages are on the form

4. Write the Execute if true script.

5. Write the Execute if false script.

6. Select Update.

G. Test Your Work


The System Administrator does not have the 'itil_admin' role, therefore you do
not have to impersonate anyone to confirm that non-California delivery fields
do not display on the Catalog Item form.

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.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 202
3. Impersonating Bow Ruggeri (this user has the 'itil_admin' role).

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.

• The Select a California location for delivery is NOT visible.


• The Select a location outside of California for delivery is visible.
• The fieldMsg advising users of the additional shipping fees is
visible below the Select a location outside of California for
delivery field in red.

7. Update the value in the California delivery? field to Yes. If the following
three actions do not occur, debug and re-test.

• The Select a California location for delivery is visible.


• The Select a location outside of California for delivery is NOT
visible.
• The fieldMsg no longer appears on the form.

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 best practice to use a
Catalog UI Policy vs. a Catalog Client Script whenever possible.

Catalog Client Scripts & Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 203
Good Prac3ces

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 204
Discuss: Why, when, and how oOen would you use the capabili3es shown in this module.

Catalog Scripts and Catalog UI Policies


© 2018 ServiceNow, Inc. All Rights Reserved 205
© 2018 ServiceNow, Inc. All Rights Reserved 206
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 207
In this module you will write, test, and debug Business Rules.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 208
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 209
Business Rules respond to all record accesses regardless of access method: forms, lists, or Web
Services.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 210
Navigate to the System Defini,on > Business Rules module to create or modify Business Rules.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 211
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 212
Navigate to System Defini,on > Business Rules and select the New bu@on to create a new Business
Rule.

Configure the Business Rule trigger:

Name – name of the Business Rule.


Applica,on – idenDfies the scope of the Business Rule. Important to correctly idenDfy the scope to
ensure the Business Rule's logic does not inadvertently impact other areas of ServiceNow.
Table – specifies the database table containing the records of interest. You can create Business
Rules on tables in the same scope as well as on tables permiGng access from another scope.
Ac,ve – if selected the Business Rule is execuDng in the runDme environment.
Advanced – select this opDon to turn on the Advanced tab for scripDng.

Although not included by default, it is recommended you add the Descrip,on field to the Business
Rule form to document the Business Rule.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 213
Configure when the Business Rule will execute:

Insert – select this check box to execute the Business Rule when a record in inserted into the
database.
Update – select this check box to execute the Business Rule when an exisDng record is updated.
Filter Condi,ons – must return true for the Business Rule logic to execute.
Role condi,ons – 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, addiDonal configuraDon opDons are available on the
When to run tab:

When – Dming of Business Rule script execuDon relaDve to the record access.
Order – order of execuDon; 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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 214
Business Rules run at different ,mes relaDve to database access.

When Query is part of the trigger condiDon, the Business Rule runs before the database query.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 215
Before Query Business Rules execute synchronously. The current Business Rule must finish
execuDon 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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 216
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 Dme perspecDve 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.

Display Business Rule


g_scratchpad.createdBy = current.sys_created_by;
g_scratchpad.caller = current.caller_id;
g_scratchpad.callerDV = current.caller_id.getDisplayValue();

Client Script
if(g_scratchpad.createdBy == 'admin'){
g_form.setValue('opened_by',g_scratchpad.caller,
g_scratchpad.callerDV);
}

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 217
Before Business Rules execute synchronously. The current Business Rule must finish execuDon
before the next Business Rule runs.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 218
A8er Business Rules execute synchronously. The current Business Rule must finish execuDon before
the next Business Rule runs.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 219
Async Business Rules are queued by the scheduler to run as soon as they can be fit in, this allows
the current transacDon to finish without waiDng 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 creaDng the associated scheduled job. By convenDon, 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 execuDon, 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.

TIP FROM FIELD


Use Async in place of A8er when immediate response is not required. The user will not
have to wait on the Business Rule to finish before they can conDnue to work.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 220
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 221
Configure what the Business Rule will do:

Set field values – set values for fields in the selected Table using the choice lists.
Add message – select this checkbox to idenDfy 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 ac,on – select this check box to abort the current database transacDon. If you select this
opDon, you cannot perform addiDonal acDons on the record. You can sDll display a message to users
by selecDng the Add message checkbox and composing the message.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 222
Use the scripDng fields on the Advanced tab when the Business Rule’s condiDons and acDons are
more complex. Example: evaluaDng the previous value of a field.

Condi,on – create a JavaScript statement to specify when the Business Rule should execute. The
CondiDon field returns true when lee blank.
Script – JavaScript that executes server-side when the When to run criteria is met and the
Condi,on field returns true. Insert the appropriate script logic to be processed when the Business
Rule executes.

IMPORTANT
CondiDon(s) on the When to run tab and condiDon(s) in the CondiDon field on the
Advanced tab must both evaluate to true for the logic in the Script field to execute.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 223
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 224
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 Dmes, 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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 225
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 relaDonships 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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 226
Expand the Fields category to see the list of variables in the current object.

InformaDonal icons indicate the source and type of each field.


• A table icon indicates the field references another table. Expand the Reference Object to select
the field of interest from that table.
• A blue circle indicates the field resides on the current table.
• A red square indicates the field resides on a parent table.
• An Index field icon indicates the field is part of one or more indexes.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 227
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 228
Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 229
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().

The gs.addInfoMessage() and gs.addErrorMessage() methods are helpful debugging strategies


during class, because the feedback is immediate. This strategy can be less effecDve in an
environment with mulDple administrators as they will see your messages at the top of the form.

TIP FROM THE FIELD


The default source for the gs.log() methods is ***Script. To use a different source, pass an
opDonal source parameter to the method. Then save a query locaDng all the records in
your source as a favorite. Example:

gs.log("The value of State: " + current.state, "Fred's


Logs");

IMPORTANT
Keep in mind, If you are developing in a scoped applicaDon, you will not be able to use
gs.log(). Error, warn, info, and debug logging methods are intended for Scoped
ApplicaDons, but can be used in the Global Scope. These logging methods provide
verbosity levels to a log message.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 230
To locate a specific Business Rule in the Debug Output look for the string ==> '<Business Rule
Name>' (Ctrl-F/Cmd-F). All debugging informaDon following that string unDl the string <==
'<Business Rule Name>' pertains to the Business Rule.

In the example shown the Business Rule name is 'Logging Methods'.

Select System Security > Debugging > Stop Debugging to stop wriDng debugging output to forms.

IMPORTANT
Remember to disable the debugger when you are done tesDng, because debugger
consumes resource when it is enabled.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 231
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>

In the example shown, the acDve field's value changed from 1 to 0.

This strategy allows you to see changed values for all fields changed by Business Rules.

Select System Security > Debugging > Stop Debugging to stop wriDng debugging output to forms,
as the Debugger can cause performance issues in a ProducDon instance.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 232
The Script Debugger offers:
• The ability to step through your script line-by-line.
• Set and remove breakpoints.
• Pause a script at a breakpoint.
• Step into and out of funcDon and method calls.
• View the value of local and global variables in real Dme.
• View the value of private variables from funcDon closures.
• View the call stack.
• View the transacDon the system is processing.

Requires the script_debugger or the admin or role.

The Script Debugger can also be launch in the Studio by selecDng File > Script Debugger.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 233
The Script Debugger is session specific; no other users are impacted. Each user can only have one
Script Debugger console open and execuDng at a Dme.

Administrators can use the Script Debugger while impersonaDng another user, but only if the
impersonated user has the admin or script_debugger role and has read access to the target script.

While impersonaDng another user you can:


• See and change breakpoints that belong to the impersonated user.
• View and pause on scripts that the impersonated user has read access to.
• The Script Debugger step-through controls also use the read access of the impersonated user.
For example, if the impersonated user does not have read access to a funcGon in the call stack,
any Step into acGon instead becomes a Step over acGon.
• The impersonated debugging session lasts unDl:
- You stop impersonaDng the user.
- You log out or the user session ends.
- You pause the Script Debugger.
- You close the Script Debugger.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 234
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 transacDon remains open as long as the user session is valid. If the user logs out, or the
session Dmes out (which will occur if paused for too long), the system stops the debugger
transacDon. If this occurs, it can be re-enabled by selecDng the on bu@on, pressing F2, or by closing
and re-opening the debugger.

TIP FROM THE FIELD


Breakpoints do not need to be removed from a script. If you would like to debug at
another Dme with the same breakpoints, simply close the Script Debugger window to turn
off debugging. The script will execute without pausing at breakpoints unDl you open the
Script Debugger again. This strategy makes it easy for you to control when you want to
debug your scripts.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 235
Breakpoints are an intenDonal stopping or pausing place in a script, for debugging purposes.

The Script Debugger lists all of the logged-in user’s Breakpoints across the plarorm (regardless of
scope). The arDfacts are listed by script type, script name, and line number. The Script Debugger
updates this list as you add and remove breakpoints in real Dme.

In the coding pane, current breakpoint is highlighted in red and inacDve breakpoints are highlighted
in blue.

Select a breakpoint to remove it.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 236
Transac,on details can be used to:
• Inspect the URL of the currently paused transacDon.
• Inspect request parameters for the currently paused transacDon.
• Inspect network informaDon about the current transacDon.
• Inspect the user and session ID that iniDated the debug transacDon.
• Parameters of the HTTP request (if they exist).

See ServiceNow's Product DocumentaDon for the full list of Available Transac,on Details and their
descripDons.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 237
The Coding Pane Header displays the script type and name of the script currently in the coding
pane.

Scripts are read-only when viewed in the Coding Pane.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 238
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 unDl it is
restarted. If the Script Debugger is already paused, the Start Debugging icon will display instead.
Resume Script Execu,on (F9) – advances from the current breakpoint to the next breakpoint. If no
breakpoints exist, the script runs to compleDon.
Step Over Next Func,on Call (F8) – advances to the next evaluated line of script based on current
condiDons. The Script Debugger skips any lines of code that do not run because their condiDons are
not met. For example, when the condiGon of an if() statement is not true, the Script Debugger skips
the code block for the condiGon.
Step Into Next Func,on 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 posiDon 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 Func,on (Shie + 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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 239
Variable informaDon 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 funcDon closure.
Global – displays a list of global scope variable names and their values.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 240
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 informaDon.

OFF – displays when the Script Debugger is inacDve and does not pause scripts or display debugging
informaDon. The Script Debugger turns off when a user pauses or closes the Script Debugger, the
user session Dmes-out or ends for any reason, or the Administrator resets all Script Debugger
instances by navigaDng to the debugger_reset.do page.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 241
By default, the plarorm supports debugging [(# of semaphores on the instance) /4] concurrent
transacDons. For example, if you have 12 semaphores by default 3 transacDons can be debugged at
a given point in Dme.

Administrators can specify the number of concurrent transacDons the system can debug by seGng
the glide.debugger.config.max_node_concurrency system property. The system can debug up
to [(# of semaphores on the instance) - 2] concurrent transacDons.

To see the plarorm’s Script Debugging semaphore set, type stats.do in the ApplicaDon Navigator
followed by <enter> on the keyboard. Example:
Semaphore Sets
Debug
Available semaphores: 4
Queue depth: 0
Max queue depth: 0
Maximum transacDon concurrency: 4
Maximum concurrency achieved: 0

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 242
Module Labs

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 243
Lab
Debugging Business Rules 05.01
625-30m

Lab Summary
You will achieve the following:
• In this lab, you will practice debugging 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.

3. Select the Active checkbox to make the Business Rule active.

4. Overwrite the string <your_initials> with your personal initials in the


Script on the Advanced Tab. Example:

5. Save the record, remain on the form.

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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 244
B. Practice Using the Script Debugger – Breakpoints and
Variables
1. In the Script field, set breakpoints by clicking the gutter to the left of the
lines beginning with:
• var myNum
• var priorityValue
• var createdValue

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:

_____________________________________________________________________

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 245
6. Keep the Script Debugger window open. Force the Lab 5.1 Business
Rule Debugging Business Rule to execute.

a) Open any active Incident, change the value of State to anything


except Closed.

b) Save the record, remain on the form.

7. Select Start Debugging.

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? __________________

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 246
12. Explain why the myNum variable value is sometimes undefined and
sometimes has a value:

_____________________________________________________________________

_____________________________________________________________________

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:

if(current.sys_created_on <= 'some value')…

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?

_____________________________________________________________________

C. Practice Using the Script Debugger – Current and


Previous Values
1. Keep the Script Debugger window open. Open any Incident with a
Short description value other than "This text set by the Lab 5.1 Business
Rule Debugging BR".

2. Force the Lab 5.1 Business Rule Debugging Business Rule to execute:

a) Change the State value to anything except Closed.

b) Save the record, remain on the form.

3. Select Start Debugging.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 247
4. Document the previous object's short_description field value.

a) Expand the previous: GlideRecord object in the Local variables list.

b) Record the previous value of the short_description field here:

_______________________________________________________________

5. Document the current object's short_description field value.

a) Expand the current: GlideRecord object in the Local variables list.

b) Record the current value of the short_description field here:

________________________________________________________________

6. Why are they different? Explain your reasoning:

___________________________________________________________________

___________________________________________________________________

7. Select the Next Breakpoint button as many times as needed to


complete the execution of the script.

8. Close the Script Debugger window.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 248
D. Practice Using the Script Debugger – Call Stack
In this section, you will practice using the Script Debugger when one server-side
script calls another server-side script. This feature can help you pinpoint exactly
which script needs fixing when multiple scripts are executing.

1. Navigate to System Definition > Script Includes.

Note: You will learn about Script Includes in an upcoming module, for now you
are only adding a breakpoint to the script.

2. Locate and open the SlaTargetNotification Script Include.

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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 249
8. Keep the Script Debugger window open. 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) Save (not Submit) the record, remain on the form.

9. Select Start Debugging.

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:

_____________________________________________________________________

15. Select the Next Breakpoint button one time.

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.

19. Close the Script Debugger window.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 250
E. Practice Debugging Using GlideSystem Logging Methods
1. Open the Lab 5.1 Business Rule Debugging Business Rule.

2. Select the breakpoints to remove them. (There should be no


breakpoints set in the script after this step is complete.)

3. Notice two undefined functions are called in this script:

• 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?

_____________________________________________________________________

6. Was a log message produced for the undefined


thisFunctionAlsoDoesNotExist() function? ___________________________

7. Search the log for records where Message contains thisFunction.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 251
8. Did you find the log message advising thisFunctionAlsoDoesNotExist() is
not defined?

_____________________________________________________________________

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.

F. Practice Debugging Using the Debug Business Rule


Feature
1. Select System Diagnostics > Session Debug > Debug Business Rule.

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.

a) Open a closed Incident, make any change to the record.

b) Save the record, remain on the form.

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? Explain your
reasoning:

_____________________________________________________________________

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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 252
Lab
Current & Previous 05.02
615-20m

Lab Summary
You will achieve the following:
• In this lab, you will practice using the current and previous global
objects in a Business Rule. You will create two new form fields for use in
your Business Rule. You will also have the opportunity to practice
debugging a little more. When this lab is complete, you will be able to
mark a Cloud Dimensions' Phase II requirement 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.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 253
A. Preparation
1. Create two new fields on the Incident form.

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.

d) Drag a True/False field to the form below the Description field.

e) Select the Edit this field (gear) icon on the right side of the field.

f) Configure the record:


Label: RCA included
Name: u_rca_included

g) Close the Properties window.

h) Drag a String field to the form below the RCA included field.
Label: RCA
Name: u_rca
Max length: 1000

i) Close the Properties window.

j) Select Save.

k) Close the Form Design browser tab/window.

l) Reload the Incident form to see the changes to the form.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 254
B. Create the Business Rule
1. Create a new Business Rule.

Name: Lab 5.2 RCA Included


Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: before
Order: 125
Insert: Selected (checked)
Update: Selected (checked)

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

5. Examine the pseudo-code for the script you will write:


• If the RCA field has no value and the RCA included checkbox is
selected (checked)
o De-select the RCA included checkbox (uncheck).
• Else if the RCA field has a value and the RCA included checkbox is
not selected (not checked)
o Select the RCA included checkbox (check).

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 255
6. Write the script in the try:

7. Select Submit.

C. Test Your Work


1. Open an Incident record.

2. Select (check) the RCA included checkbox.

3. Save the record, remain on the form.

4. Is the RCA included checkbox unchecked? If not, debug and re-test.

5. Enter a value of your choice in the RCA field.

6. Save the record, remain on the form.

7. Is the RCA included checkbox checked? If not, debug and re-test.

8. Does the RCA included field need to remain visible on the form?
_______________

9. Make the 5.2 RCA Included Business Rule inactive.

Lab Completion
You have successfully completed the lab and practiced using the current and
previous global objects.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 256
Lab
Display Business Rules and 05.03
Dot Walking 615-20m

Lab Summary
You will achieve the following:
• In this lab, you will practice with the g_scratchpad global object,
Display Business Rules, and dot-walking.

A. Create a Business Rule


1. Create a new Business Rule.

Name: Lab 5.3 Display Business Rule


Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: display
Order: 150

2. Examine the pseudo-code for the script you will write:

• Add the current record's Resolved By reference object's First Name


to the g_scratchpad object.
• Add the current record's Resolved By reference object's Last Name
to the g_scratchpad object.
• If there is no value in reopen_count
o Set the g_scratchpad.reopenCount's value to zero.
• Else
o Add the current record's Reopen Count to the g_scratchpad
object.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 257
3. Write the script:

4. Select Submit.

B. Create a Client Script


1. Create a new Client Script.

Name: Lab 5.3 ResolvedBy Client Script


Table: Incident [incident]
UI Type: Desktop
Type: onChange
Field name: State
Active: Selected (checked)
Inherited: Not selected (not checked)
Global: Selected (checked)

2. Examine the pseudo-code for the script you will write:


• When the State field changes,
o If the old State is Resolved, Closed, or Canceled and the new
State is not Resolved, Closed, or Canceled
§ Display a confirmation box stating the Incident was previously
resolved by <user who closed the record> and how many
times the Incident has been reopened. Confirm the user really
wants to reopen.
§ If the user cancels reopening the Incident
• Set the State back to the old State value.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 258
3. Write the script:

4. Select Submit.

C. Test Your Work


1. Open an Incident in a Resolved state.

2. If the Resolved by field has no value, enter the user of your choice and
Save the Incident.

3. Change the State to In Progress.

4. Did the confirmation dialog box appear? Did the g_scratchpad


properties resolve correctly? If not, debug and re-test.

5. Select the Cancel button in the confirmation dialog box.

6. What happened to the State field? Is this the expected behavior? If not,
debug and re-test.

7. Change the State to In Progress.

8. This time select the OK button in the confirmation dialog box.

9. Save the record, remain on the form.

10. Set the State to Resolved.

11. Save the record, remain on the form.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 259
12. Set the State to In Progress.

13. Did the reopen count increase by 1 correctly? If not, debug and re-
test.

14. Make the Lab 5.3 Display Business Rule inactive.

15. Make the Lab 5.3 ResolvedBy Client Script inactive.

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!

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 260
Lab 5.2 fulfills requirement 3.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 261
Good PracDces

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 262
Discuss: Why, when, and how oeen would you use the capabiliDes shown in this module.

Business Rules
© 2018 ServiceNow, Inc. All Rights Reserved 263
© 2018 ServiceNow, Inc. All Rights Reserved 264
GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 265
GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 266
GlideSystem methods all begin with gs. For example, the method gs.addInfoMessage() displays
informa9onal 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.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 267
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.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 268
This example shows the different values returned by the getUserXXXX() methods.

addInfoMessage() – adds a blue informa9onal message to the top of a form or list.


addErrorMessage() – adds a red warning message to the top of a form or list.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 269
getProperty() – returns the value of a Glide property.
getPreference() – gets a user preference.
getDisplayColumn() – gets the display column for the table.
tableExists() – determines if a database table exists.
nil() – returns true if a field's value is null or an empty string ("").
eventQueue() – queues an event for the event manager.
print() – writes a message to the system log.
log() – logs a message to the system log and saves it to the syslog table.
logError() – logs an error to the system log and saves it to the syslog table.
getMessage() – retrieves translated messages to display in the UI.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 270
GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 271
beginningOfLastWeek() – date and 9me for the beginning of last week in GMT (yyyy-mm-dd
hh:mm:ss).
beginningOfNextMonth() – date and 9me for the beginning of next month in GMT.
dateDiff() – calculates the difference between two dates.
endOfLastWeek() – date and 9me for the end of last week in GMT.
endOfNextMonth() – date and 9me for the end of next month in GMT.
minutesAgo()/daysAgo()/quartersAgo()/monthsAgo()/yearsAgo() – returns the date and 9me a
specified number of minutes/quarters/months/years ago. Nega9ve numbers will show a date and
9me in the future.
now() – current date.
nowDateTime() – current date and 9me in the user-defined format.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 272
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 9me
in the user's 9me zone rather than in GMT.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 273
The GlideDateTime class provides methods for performing opera9ons on GlideDateTime objects,
such as instan9a9ng GlideDateTime objects or working with glide_date_6me fields.

In addi9on to the instan9a9on methods described above, a GlideDateTime object can be


instan9ated from a glide_date_6me field using the getGlideObject() method (for example, var gdt =
gr.my_date9me_field.getGlideObject();).

Note: Methods can use the Java Virtual Machine 9me zone, so use equivalent local 9me and UTC
methods whenever possible to prevent unexpected result.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 274
The complete set 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 led.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 275
Module Labs

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 276
Lab
Setting the CAB Date 06.01
610-15m

Lab Summary
You will achieve the following:
• In this lab, you will write a Business Rule using GlideSystem date and
time methods to set the CAB date for a Change Request to
Wednesday of next week. When this lab is complete, you will 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.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 277
A. Create a Business Rule
1. Create a new Business Rule.

Name: Lab 6.1 Set CAB Date


Table: Change Request [change_request]
Active: Selected (checked)
Advanced: Selected (checked)
When: before
Order: 300
Insert: Selected (checked)

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

5. Examine the pseudo-code for the script you will write:


• Set the CAB date to next Monday.
• Convert the CAB date to a numeric value (UNIX time format).
• Calculate the number of milliseconds in two days.
• Add two days to the CAB date.
• Set the CAB date to Wednesday next week.

6. Write the script in the try block:

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 278
7. Select Submit.

B. Test Your Work


1. Create a new Change Request.

2. Select Normal: Changes without predefined plans that require


approval and CAB authorization.

3. Enter Testing Lab 6.1 in the Short description field.

4. Save the record, remain on the form.

5. Navigate to the Schedule tab.

6. Is the CAB date correct? If not, debug and re-test.

7. Make the Business Rule inactive.

Lab Completion
Great job! You successfully completed the requirement and practiced using
many different GlideSystem methods in a server-side script.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 279
Lab
Re-open Problem Date
06.02
Validation 610-15m

Lab Summary
You will achieve the following:
• In this lab, you will 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. When this lab is
complete, you will mark a Cloud Dimensions' Phase II requirement
complete.

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.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 280
A. Create a Business Rule
1. Create a new Business Rule.

Name: Lab 6.2 Reopen Problem Date Validation


Table: Problem [problem]
Active: Selected (checked)
Advanced: Selected (checked)
When: before
Order: 200
Update: Selected (checked)

2. Examine the pseudo-code for the script you will write:


• If the record changes from inactive to active
o Read today's date into a variable.
o Read the Closed date into a variable.
o Determine the difference between today and the closed date.
o Calculate 30 days, read the answer into a variable.
o If the number of days between today and the Closed date is
larger than 30,
§ Add an error message to the form page.
§ Abort the Save/Update and do not write to the database.

3. Write the script.

a) Switch to the Advanced tab.

b) Write the Condition:

previous.active == false && current.active == true

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 281
c) Write the script:

4. Select Submit.

B. Test Your Work


1. Open any closed Problem record.

2. Ensure the value in the Closed field (on the Closure Information tab) is
greater than 30 days. Select an older date and save the record if
necessary.

3. Select a State other than Closed/Resolved.

4. Save the record, remain on the form.

5. Do you see an error message at the top of the form? If not, debug and
re-test.

Note: The 'Invalid update' error message is a result of the aborted save and the
date in the 'Closed' field remains unchanged.

6. Make the Business Rule inactive.

Lab Completion
Well done! You successfully completed the requirement and practiced
comparing dates in the Global space using GlideSystem methods.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 282
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 applica9on. 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 led.

IMPORTANT
The Scoped GlideSystem API does not provide methods to work with date/9me fields. Use
GlideDate or GlideDateTime methods (Scoped and Legacy). Detailed informa9on on both
of these APIs can be found on the ServiceNow Developer site.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 283
Scoped GlideSystem logging methods are available for scripts in private applica9on scopes.
debug() – sets the log Level to 'Debug'. Use to log informa9onal messages useful for debugging.
error() – sets the log Level to 'Error'. Use to log messages that might s9ll allow the system to
con9nue running.
info() – sets the log Level to 'Informa9on'. Use to log informa9onal messages describing progress.
warn() – sets the log Level to 'Warning'. Use to log poten9ally harmful messages.
isDebugging() – determines if debugging is ac9ve 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 bohom of a form
when System Debugging is turned on.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 284
If using logging methods in produc9on, always select the appropriate log type for the event or log
message (error, info, warn or debug).

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 285
Lab 6.1 fulfills requirement 4.
Lab 6.2 fulfills requirement 5.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 286
GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 287
Discuss: Why, when, and how oden would you use the capabili9es shown in this module.

GlideSystem
© 2018 ServiceNow, Inc. All Rights Reserved 288
GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 289
GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 290
Any table row from any table can become a GlideRecord.

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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 291
This strategy outlines the necessary steps for crea>ng and popula>ng a GlideRecord object, then
processing any returned records.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 292
The example creates a variable called myObj which is a GlideRecord object for the Change Request
[change_request] table.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 293
The example shown only builds the select statement; it does not execute it.

TIP FROM THE FIELD


In a SQL statement , the “where” clause has a direct effect on how long it takes to return
data. Since the query condi>ons generate a SQL statement, use the appropriate query
condi>ons and the right number of them to generate the correct “where” clause. If you do
not use the right query condi>ons, performance of a query can be degraded.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 294
Numeric comparison operators:
> field must be greater than the value supplied.
>= field must be equal or greater than the value supplied.
< field must be less than the value supplied.
<= field must be equal or less than the value supplied.

String comparison operators:


STARTSWITH – field value must start with the value supplied.
ENDSWITH – field value must end with the value supplied.
CONTAINS – field value must contain the value supplied somewhere in the text.
DOES NOT CONTAIN – field value must not have the value supplied anywhere in the text.

Both numeric and string comparison operators:


= field must be equal to the value supplied.
!= field must not equal the value supplied.

See ServiceNow's Product Documenta>on for informa>on on addi>onal operators.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 295
The _query() method provides the same func>onality 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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 296
.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 condi>on. 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 func>onality 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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 297
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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 298
To automa>cally 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 addOrCondiBon() method, use the script macro vargror.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 299
Use an object variable and addQuery() to add the first condi>on and addOrCondiOon() for the
second condi>on.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 300
Each 'group' in the select statement is its own object in the script.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 301
Defines a GlideRecord based on the specified expression of name = value. If value is not specified,
then the expression used is sys_id = name.

This method performs a next() opera>on before returning.

TIP FROM THE FIELD


If you are not 100% sure the get() method will return a record, consider using an if()
condi>on to first check if you retrieved a GlideRecord. If not, script logic can be wri_en to
handle that scenario.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 302
Both of these op>ons return the number of rows mee>ng the query criteria.

The first op>on, 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 fast
execu>on. 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 con>nuously. If in doubt, use this strategy.

See the ServiceNow Developer site for more informa>on on the GlideAggregate API.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 303
Although this example looks overwhelmingly complex, it is easy to build the where clause(s) using
the Condi>on builder.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 304
Remember, you can type <table name>.list into the Applica>on 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 selec>ng Copy query, the query copied to the clipboard
will contain only those parts of the query from where you clicked and to the lee. 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 en>re set of where clauses.

IMPORTANT
Always test queries on a development instance prior to deploying them to a produc>on
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
condi>on 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 deleteMulOple() method on bad query results can result in data loss.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 305
For example, the baseline SNC - ITIL - Close Related Business Rule closes all related Incident records
when a Problem record closes. The Business Rule iden>fies the Problem table in its trigger, and the
GlideRecord query updates the appropriate Incident records.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 306
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 lee.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 307
GlideRecord can handle a variety of data manipula>on tasks, but can it restrict data to certain
users? Yes, the GlideSystem methods discussed in Module-6, like hasRole(), canRead(), and
canWrite() used in conjunc>on with GlideRecord will restrict data to users that have the right roles.
However, you must include the appropriate condi>onal checks every >me data is queried. This
strategy is NOT considered best prac>ce.

GlideRecord example GlideRecordSecure example


var count = 0; var count = 0;
var gr = new GlideRecord('mytable'); var grs = new GlideRecordSecure('mytable');
gr. query(); grs.query();
while (gr.next()) { while (grs.next()) {
if (!gr.canRead()) continue; grs.val = "val-" + grs.id;
if (!gr.canWrite()) continue; if (grs.update())
if (!gr.val.canRead() || ! count ++;
gr.val.canWrite()) }
gr.val = null;
else
gr.val = "val-" + gr.id;
if (gr.update())
count ++;
}

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 308
Module Labs

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 309
Lab
Two Glide Record Queries 07.01
620-25m

Lab Summary
You will achieve the following:
• In this lab, you will write a GlideRecord query to locate a set of
Incidents, then a second GlideRecord query to locate a set of users.
• The second script has you trigger the Business Rule from one table, but
make updates to records on a different table. A good strategy to
practice.

A. Script 1: Find Active SAP Incidents


1. Create a new Business Rule.

Name: Lab 7.1 SAP Incidents


Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: after
Order: 150
Insert: Selected (checked)
Update: Selected (checked)

2. Switch to the Advanced tab.

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
align the script.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 310
5. Update the Script Macro to suit your current requirements.

a) Update the name of the GlideRecord object to something more


meaningful (considered best practice).

b) Replace the word "if" with while.

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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 311
7. Now update the Script to identify the Incidents matching the query
criteria by their Number. You can use this script as a guide, or any other
identification strategy of your choice.

8. Select Submit.

B. Test Your Work


1. Type incident.list in the Application Navigator’s Search field, and press
<Enter> on your keyboard to open the list view of the Incident table.

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.

5. Save the record, remain on the form.

6. Did your script locate the expected records? If not, debug and re-test
your Business Rule.

7. Make the Lab 7.1 SAP Incidents Business Rule inactive.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 312
C. Script 2: Update Executive User Records
1. Using the GlideRecord strategies, you have learned so far, create, test,
and debug a GlideRecord query on your own.

a) Find all users with Vice, VP, or Chief in their title.

b) Make the users VIPs.

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.

3. Make the Business Rule inactive.

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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 313
D. Business Rule Example for Script 2
1. Create a new Business Rule.
Name: Lab 7.1 VIP Users
Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: after
Order: 100
Insert: Selected (checked)
Update: Selected (checked)

Script:

2. Test the 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.

b) Create a new Incident.

c) Submit the record.

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.

f) Make the Business Rule inactive.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 314
Lab
RCA Attached: Problem and 07.02
Child Incidents 620-25m

Lab Summary
You will achieve the following:
• In this lab, you will 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.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 315
A. Create a Business Rule
1. Create a new Business Rule.

Name: Lab 7.2 RCA Update PRB and Child INCs


Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: after
Order: 100
Insert: Selected (checked)
Update: Selected (checked)
Condition: current.state.changesTo(IncidentState.CLOSED)

2. Examine the pseudo-code for the script you will write:


• When the value of State changes to Closed
o If the Problem field has a value
§ Create a new GlideRecord object for the Problem table
§ Get the current Problem into the new GlideRecord object
§ Update the Problem's Work notes with the RCA source and
current value of RCA
o Create a new GlideRecord object for the Incident table
o Query for incidents where the value of Parent Incident is the
same as the current Incident
o Query the database
o While there are records returned
§ Update the Child Incident's RCA field to indicate the RCA
source and current value of RCA

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 316
3. Write the script:

4. Select Submit.

B. Test Your Work


1. Create a new Incident.

a) Configure the record:


Caller: <Select any User of your choice>
Short description: THIS IS MY PARENT INCIDENT
Problem (Related Records tab): <Select any "active" Problem
record>

b) Write the Problem number you chose here: ___________________.

c) Write the Incident number here: ___________________.

d) Select Submit.
2. Create another new Incident.

a) Configure the record:

Caller: <Select any User of your choice>


Short description: This is Child Incident #1

b) Select Submit.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 317
3. Create another new Incident.

a) Configure the record:

Caller: <Select any User of your choice>


Short description: This is Child Incident #2
Set the Parent Incident to the Incident from step 1.

b) Select Submit.

4. Open the Parent Incident from step 1.

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.

6. Update these fields:

RCA: Parent Incident RCA field contents


State: Closed
Resolution code: Solved (Permanently)
Resolution notes: Resolution notes from my Parent Incident

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.

10. Make the Business Rule inactive.

11. Set the Parent Incident to the Incident from step 1.

Lab Completion
Well done! You have successfully updated records on two different tables using
one Business Rule.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 318
Lab
addEncodedQuery() 07.03
65-10m

Lab Summary
You will achieve the following:
• In this lab, you will 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).

2. Rename the Business Rule Lab 7.3 addEncodedQuery.

3. Make the script Active.

4. Select Insert on the form's Context menu.

5. Navigate to User Administration > Users.

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.

8. Run the query.

9. Record the number of records meeting the criteria here:


_______________.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 319
10. Right-click the right-most condition of the query in the breadcrumbs and
select Copy query.

B. Modify the Script


1. Re-write the Lab 7.3 addEncodedQuery Business Rule script to use the
addEncodedQuery() method.

a) Delete any script statements that are no longer needed.

b) Add the addEncodedQuery() method to the script.

c) Paste the copied query from your clipboard into the


addEncodedQuery() method as the parameter.

2. Select Update.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 320
C. Test Your Work
1. Force the Lab 7.3 addEncodedQuery Business Rule to execute.

2. Was the expected number of records returned? If not debug and re-
test your Business Rule.

Make the Business Rule inactive.

Lab Completion
Good job! You have successfully used the addEncodedQuery() GlideRecord
method.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 321
Follow these steps to locate Scoped GlideRecord informa>on ServiceNow Developer site.
1. Select API.
2. Select Server.
3. Select SCOPED.
4. Locate and expand the GlideRecord category on the lee.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 322
Lab 7.2 fulfills requirement 6.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 323
GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 324
Discuss: Why, when, and how oeen would you use the capabili>es shown in this module.

GlideRecord
© 2018 ServiceNow, Inc. All Rights Reserved 325
© 2018 ServiceNow, Inc. All Rights Reserved 326
Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 327
Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 328
Although any server-side script can generate an event, most will be generated by Business Rules or
Workflows.

Events are not ac@ons but rather an entry in the Event Queue.

Logic must be wriCen to respond to entries in the Event Queue and take ac@on.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 329
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.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 330
Event name – name used in script logic to generate the event. By conven@on the event name is
<table name>.<event name>. The table_name is not automa@cally 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 troubleshoo@ng only and not for event
processing. Whenever you add an event to a script, update this field.
Descrip8on – documents the event purpose. Be sure to put a meaningful descrip@on for future
reference. If you alter the meaning of an event, update this field.
Applica8on – iden@fies the scope containing the event.
Queue – the event processing queue which manages this event. If leN 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.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 331
CAUTION!
Do not overwrite the text index events process Schedule Item!
Overwri@ng 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 crea@ng 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 poten@ally delay processing of higher
priority events. For example, if an event is generated every @me 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 Ac@on Processing @mes or rapid
genera@on of events causing high volumes in the queues.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 332
event_name – name of Event in Registry.
object – current, previous, or a GlideRecord Object.
parm1 – op@onal parameter used to pass a string. If you do not need to pass this parameter the
conven@on is to pass gs.getUserID().
parm2 – op@onal parameter used to pass a string. If you do not need to pass this parameter the
conven@on is to pass gs.getUserName().
parm3 – op@onal parameter can be used to pass the name of a queue. This parameter overwrites a
value provided by the Queue field on the Event's Registry record. Syntax example:

gs.eventQueue("problem.myInsertedProblem", current, current.number,


gs.getUserDisplayName(), "js_queue");

parm1 and parm2 can be strings ("hello world"), proper@es (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().

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 333
The @me parameter is set to a record field containing a Date/Time value. The event is generated at
the @me passed in this field.

The example shown calls the registered event and passes it the current object, the string "Event
@me:" + the value in the current.u_reminder field, the value of gs.getUserName(), and the date/@me
for the event to be generated.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 334
Created – date and @me 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 @me the event was processed. This @me reflects the locale of the machine
running the ServiceNow instance.
Processing dura8on – @me taken to process this event in milliseconds.
Queue – processor queue name.

The Processed @me should be within 30 seconds (or whatever the Interval is for the Schedule Item)
of the Created @me.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 335
Scripts can be set to execute whenever a par@cular ac@vity occurs in the system, rather than at a
par@cular @me. Navigate to System Policy > Events > Script Ac8ons to create a new Script Ac@on.

Name – name of the Script Ac@on.


Event name – registered event to use for this Script Ac@on.
Order – order in which the Script Ac@on executes.
Applica8on – the scope containing the Script Ac@on.
Ac8ve - selected the check box (true) to enable the Script Ac@on. Note: not selected by default.
Condi8on script – script the condi@ons under which the Script Ac@on should execute.
Script – script the logic to execute when the Script Ac@on runs.

The event and current objects do not exist in the Condi8on script field. Tes@ng for condi@ons using
these objects must be done in the Script field. Example: if(event.parm1 == 'itil').

TIP FROM THE FIELD


Use this code to see the event object proper@es.

var output = "";


for (var property in event) {
output += property + ': ' + event[property]+', ';
}
gs.log("Event Object Properties: " + output);

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 336
Module Labs

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 337
Lab
Tracking Impersonations 08.01
610-15m

Lab Summary
You will achieve the following:
• In this lab, you will respond with a Script Action to the baseline
impersonation.start event. When this lab is complete, you will 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 ServiceNow 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.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 338
A. Review the Event Registry Record
1. Review the impersonation.start Event Registration record.

a) Navigate to System Policy > Events > Registry.

b) Locate and open the impersonation.start record.

c) Review the value in the Description field:


i. Record the value passed in event.parm1 here: ________________.
ii. Record the value passed in event.parm2 here: ________________.

2. Close the record.

B. Create a Script Action


3. Create a new Script Action.

a) Open System Policy > Events > Script Actions.

b) Select New.

c) Configure the trigger:

Name: Lab 8.1 Tracking Impersonations


Event name: impersonation.start
Active: Selected (checked)

4. Examine the pseudo-code for the script you will write:

Log the name of the user doing the impersonation and the user being
impersonated.

5. Write the script:

6. Select Submit.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 339
C. Test Your Work
1. Impersonate Beth Anglin.

2. While impersonating Beth Anglin, impersonate Fred Luddy.

3. End the impersonation. You should be logged in as the System


Administrator when this step is complete.

4. Open System Policy > Events > Event Log.

5. Locate the two impersonation.start events.

6. Examine Parm1 for the two events. What value does Parm1 have?
Record the value here:

__________________

7. Is this the value you expected?

_____________________________________________________________________

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.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 340
Lab
Incident State Event 08.02
610-15m

Lab Summary
You will achieve the following:
• In this lab, you will register, generate, and respond to an event. The
Event is triggered by changes to the Incident State.

A. Register a New Event


1. Navigate to System Policy > Events > Registry.

2. Select New.

3. Configure the record:

Event name: incident.state.changed


Table: Incident [incident]
Fired by: Lab 8.2 Incident State Changed Business Rule
Description: Fires when the value in the State field changes

4. Select Submit.

B. Trigger an Event
1. Create a new Business Rule.

Name: Lab 8.2 Incident State Changed


Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: after
Order: 300
Insert: Selected (checked)
Update: Selected (checked)
Condition: current.state.changes()

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 341
2. Examine the pseudo-code for the script you will write:

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.

3. Write the script.

4. Select Submit.

C. Respond to the Event


1. Create a new Script Action.

a) Open System Policy > Events > Script Actions.

b) Select New.

c) Configure the trigger:

Name: Lab 8.2 Incident State Changed


Event Name: incident.state.changed
Active: Selected (checked)

d) Examine the pseudo-code for the script you will write:

Store parm1's value in a variable.


Store parm2's value in a variable.
Log the old and new Incident States in a warning message.

e) Write the script:

f) Select Submit.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 342
D. Test Your Work
1. Open and modify an existing Incident.

a) Record the value of State here: ___________________.

b) Change the State to a different value.

c) Record the modified value of State here: ___________________.

d) Select Update.

2. Did the event occur?

a) Open System Policy > Events > Event Log.

b) Locate the incident.state.changed event in the Name column.

c) Are the parm1 and parm2 values what you expected? If not,
debug and re-test the Business Rule.

3. Was the event responded to?

a) Open System Logs > System Log > Script Log Statements.

b) Locate your Script Action message.


i. Change the Search field type to Message.
ii. Enter <YOUR INITIALS> Script in the Search field.
iii. Press the <enter> key on your keyboard.

4. If needed, debug and re-test the Script Action.

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.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 343
Lab 8.1 fulfills requirement 10.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 344
Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 345
Discuss: Why, when, and how oNen would you use the capabili@es shown in this module.

Script an Event
© 2018 ServiceNow, Inc. All Rights Reserved 346
Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 347
In this module you will write, test, and debug UI Policies.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 348
Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 349
Script Includes load only on demand and do not impact performance.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 350
Navigate to System Defini,on > Script Includes to create or modify Script Includes.

You should not modify the behavior of baseline Script Includes.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 351
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 opDon if client-side scripts can call the Script Include.
Applica,on – idenDfies the scope of the Script Include.
Accessible from – sets the accessibility of the Script Include.
• All applicaDon scopes: sets the Script Include to be global, and can be accessed from any script.
• This applicaDon scope only: sets the Script Include to be private and can only be accessed by
other scripts in the same scope.
Ac,ve – select this opDon if the Script Include is executable. If this opDon is not selected the Script
Include will not run even if called from another script.
Descrip,on – (opDonal but highly recommended) documentaDon explaining the purpose and
funcDon 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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 352
If a script is to be used mulDple Dmes, it should be stored as a Script Include method.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 353
Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 354
Classless/on-demand Script Includes are not callable from the client-side even if the Client callable
opDon is selected.

Delete the code template automaDcally inserted in the Script field aOer the Script Include is named.

If a second funcDon is included in the script, it is only available for use aOer the first funcDon has
executed. This strategy is not considered best pracDce. If you wish to create a script with mulDple
funcDons, it is bePer to define a new Class or extend an exisDng Class.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 355
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 funcDon.

You will see later in this module how Class-based Script Includes are handled differently.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 356
Module Labs

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 357
Lab
Classless Script Include 09.01
610-15m

Lab Summary
You will achieve the following:
• In this lab, you will create, test, and debug a classless Script Include to
write logging messages for server-side scripts.

A. Create a Classless Script Include


1. Navigate to System Definition > Script Includes.

2. Select New.

3. Configure the record:

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.

5. Examine the pseudo-code for the script:


• Create a new function that will be passed a string when it is called.
o Set the debug property on the object to true.
o Set the debugPrefix property on the object to <YOUR INITIALS>:
o If the debug property is true
§ Write a log message containing the debugPrefix property
and the passed in string.

6. Write the script:

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 358
7. Select Submit.

B. Use the Classless Script Include


1. Create a new Business Rule.
Name: Lab 9.1 Script Include Logging
Table: Incident [incident]
Active: Selected (checked)
Advanced: Selected (checked)
When: After
Insert: Selected (checked)
Update: Selected (checked)

2. Examine the pseudo-code for the script:


• For the properties in the current object
o If the property has a value
§ Call the Logging Script Include function and pass
§ Set the property and the property value.

3. Write the script:

4. Select Submit.

C. Test Your Work


1. Create a new Incident and populate many of the fields with values of
your choice.

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 359
4. Modify the Script Include by setting this.debug = false.

5. Create a new Incident and populate the fields with the values of your
choice.

6. Submit the Incident.

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 360
Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 361
Once a Script Include is named, a Script Editor Macro is automaDcally 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 automaDcally update to reflect the change.

TIP FROM THE FIELD


Script Includes/Class names oOen include a table name (e.g. IncidentUDls, ChangeUDlsSNC,
KBUDls) as a way to group/manage funcDons. In the case of smaller applicaDons with
minimal tables, you could instead include the applicaDon name in the Script Includes/Class
name (e.g. TravelMgmtUDls).

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 362
FuncDons are separated by commas.

Type is for allowing any developer using your Script Include to idenDfy the type of object it is.
Search Community for more informaDon on the topic, quite a few blog arDcles have been wriPen by
ServiceNow experts on this advanced subject.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 363
You can also define variables and objects in the iniDalize() funcDon as well.

In this example, the logged-in user's User [sys_user] record was retrieved.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 364
Module Labs

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 365
Lab
Create a New Class 09.02
620-25m

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

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 366
A. Preparation
1. Navigate to Configuration > Base Items > Printers. (Consider saving this
module as a Favorite as you will be navigating here often throughout
this lab.)

2. Select New.

3. Add the Location field to the form.

4. Select the magnifying glass to the right of the Location field.

Note: Notice every location is available for selection. (Close this pop-up window
when you are ready to proceed.)

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 367
B. Write the Script Include to Restrict Location Selections
1. Create a new Script Include.

Name: LocationsByRole
Accessible from: All application scopes
Description: Lab 9.2 Restrict Location Options

2. Write the script.

3. Select Submit.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 368
C. Configure the Location's Reference Qualifier to Call the
Script Include
1. Navigate to Configuration > Base Items > Printers.

2. Select New.

3. Right-click the Location field’s label and select Configure Dictionary.

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.

5. Select the Advanced view Related Link.

6. Configure the fields on the Reference Specification tab.

User reference qualifier: Advanced


Reference qual: javascript:new LocationsByRole().forCMDB()

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 369
7. While you are in the Location's Dictionary Entry record, take a minute
to also disable the legacy Tree picker. (The List view is a better strategy
for locating Locations quickly as it offers the use of the Condition
builder to query the list.)

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.

D. Test Your Work


1. Navigate to Configuration > Base Items > Printers.

2. Select New.

3. Select the magnifying glass to the right of the Location field.

Notice a List view replaces the Tree picker view.

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.

5. Navigate to Configuration > Base Items > Printers.

6. Select New.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 370
7. Select the magnifying glass to the right of the Location field.

Notice only the two New York locations are available for selection. If not,
debug and re-test.

8. Impersonate Howard Johnson. A member of the Asset Managers –


Corporate Group with the asset_mgr_corporate Role, and his
Company is ACME North America.

9. Navigate to Configuration > Base Items > Printers.

10. Select New.

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 371
Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 372
Extending a Class means to add funcDonality (typically in the form of methods) to an exisDng Class
without modifying the original script.

Create a New Script Include/Class, reference an exisDng Class using the extendsObject() method to
include all its funcDonality, add script logic

Commonly extended ServiceNow Classes:


• AbstractAjaxProcessor: makes AJAX calls from Client Scripts.
• LDAPU,ls: used by LDAP integraDon to ServiceNow (e.g. adding Managers to users, managing
group membership, debug logging).
• Catalog*: set of Classes used for Service Catalog management (e.g. UI building, Form
processing).

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 373
AJAX – Asynchronous JavaScript and XML
Set of web development methods used client-side to send data to and receive data from the server.

In this example, the alertGreeDng() method is created. When it is called, it returns the string “Hello
<name passed in from the client> !” to the calling script.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 374
The code shown here would be wrapped in a funcDon (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 funcDon in the Script Include to use. All
passed in parameters must start with sysparm_.

The getXML() method is passed the name of a callback funcDon which parses properDes and values
from the XML returned from the server. (Data is oCen returned as XML but can also be returned as
a JSON object.)

The getXMLAnswer() method can be used instead of getXML(). This method automaDcally 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);

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 375
The XML in this example was captured using Firebug and has been edited to fit on the slide.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 376
Review the two scripts side-by-side.

The client-side code shown here would be wrapped in a funcDon (onLoad(), onSubmit(), or
onChange()) depending on its type.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 377
In this example, the Script Include extends the AbstractAjaxProcessor Class.

The IdenDfyTwoUsers object has a funcDon 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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 378
The client-side code shown here would be wrapped in a funcDon (onLoad(), onSubmit(), or
onChange()) depending on the type of client-side script.

In this example, the answerFromXML variable from the response contains mulDple pieces of
informaDon 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 unDl the first
colon, and user[1] contains the value from the colon to the end of string. Assume answer =
MaP:Miranda. In this case user[0] = ”MaP” and user[1] = ”Miranda”.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 379
Module Labs

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 380
Lab
HelloWorld GlideAjax 09.03
610-15m

Lab Summary
You will achieve the following:
• In this lab, you will create a Script Include which extends the
AbstractAjaxProcessor class. The Script Include will be called from a
Client Script.

A. Create a Script Include


1. Create a new Script Include.
Name: HelloWorld
Client Callable: Selected (checked)
Accessible from: All application scopes
Active: Selected (checked)
Description: Lab 9.3 Extends the AbstractAjaxProcessor class

2. Examine the pseudo-code for the script:


• Create a new class called HelloWorld.
• Create an object from the new class with properties inheritable by
other objects and which extends the AbstractAjaxProcessor class.
o Add a method to the new object called alertGreeting.
§ Return "Hello" + parameter containing user's name + "!".

3. Write the Script:

4. Select Submit.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 381
B. Call the Script Include from a Client Script
1. Create a new Client Script.
Name: Lab 9.3 HelloWorld Client Script
Table: Incident [incident]
Type: onLoad
Active: Selected (checked)
Global: Selected (checked)

2. Examine the pseudo-code for the script:


• Create an instance of the GlideAjax object called HelloWorld.
• Add a param to call the alertGreeting method.
• Add a param to pass the user name Ruth.
• Use the getXML method and the callback function HelloWorldParse
to execute the Script Include.
• Pass the response returned from the Script Include to the callback
function.
• Locate the answer variable in the returned XML and store the value
in a variable.
o Generate an alert to display the value of the answerFromXML
variable.

3. Write the script:

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?

_____________________________________________________________________

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 382
C. Test Your Work
1. Open any Incident.

2. Did an alert appear? Was it populated correctly? If not, debug and re-
test.

3. Make the Lab 9.3 HelloWorld Client Script inactive.

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 383
Lab
Number of Group Members 09.04
620-25m

Lab Summary
You will achieve the following:
• In this lab, you will create a Script Include which extends the
AbstractAjaxProcessor. The Script Include will be called from a Client
Script. The Client Script will pass a Group name to the Script Include
and the number of members of that group will be returned.

A. Create a Script Include


1. Create a new Script Include.
Name: AssignmentGroupUtils
Client Callable: Selected (checked)
Accessible from: All application scopes
Active: Selected (checked)
Description: Lab 9.4 extends the AbstractAjaxProcessor class.
Returns the number of members in a Group.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 384
2. Examine the pseudo-code for the script:
• Create a new class called AssignmentGroupUtils.
• Create an object from the new class with properties inheritable by
other objects and which extends the AbstractAjaxProcessor class.
o Add a method to the new object called countGroupMembers.
§ Create a new variable to store the group name.
§ Store the message the group has no members in the variable
message.
§ Store the sys_id of a group from a Client Script in the variable
groupID.
§ Create a new GlideRecord object for the sys_user_grmember
table.
§ Query the sys_user_grmember table to return records for all
members of the group passed in from a Client Script.
§ If there are records returned
• Store the name of the group in the variable grpName.
§ If the value of grpName is not empty
• Overwrite the current value in the variable message with a
string containing the name of the group and number of
group members in the variable message
• Return the variable message to the calling Client Script.

3. Write the script:

4. Select Submit.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 385
B. Call the Script Include from a Client Script
1. Create a new Client Script.
Name: Lab 9.4 Number of Group Members
Table: Incident [incident]
Type: onChange
Field name: Assignment group
Active: Selected (checked)
Global: Selected (checked)

2. Examine the pseudo-code for the script:


• Create an instance of the GlideAjax object called
AssignmentGroupUtils.
• Add a param to call the countGroupmembers method.
• Add a param to pass the sys_id of the Assignment group value to
the Script Include.
• Use the getXML method and the callback function membersParse
to execute the Script Include.
• Pass the response returned from the Script Include to the callback
function.
o Locate the answer variable in the returned XML and store the
value in a variable.
o Generate an alert to display the value of the answer variable.

3. Write the script:

4. Select Submit.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 386
C. Test Your Work
1. Navigate to User Administration > Groups.

2. Select a group with members assigned to it. Record the group you
selected here:

_______________________________

3. Open any Incident record.

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.

D. Reuse the Script Include


1. Can you think of other tables that could use a similar Client Script to
call the same Script Include? Write the name of two of those tables
here:

_____________________________________________________________________

2. Open the Lab 9.4 Number of Group Members Client Script.

3. Update the Client Script trigger:

Name: Lab 9.4 Number of Group Members (PRB)


Table: Problem [problem]

4. Select Insert on the form's Context menu.

5. Open any Problem record.

6. Change the value in the Assignment group field to the group you
selected earlier in the lab.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 387
7. Did the alert appear? Was it populated correctly? If not, debug and
re-test.

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 388
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 properDes/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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 389
In the example shown, four objects are contained in the array sent back.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 390
The client-side code shown here would be wrapped in a funcDon (onLoad(), onSubmit(), or
onChange()) depending on the type of client-side script.

The JSON.parse() method creates an object from a JSON formaPed string.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 391
Module Labs

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 392
Lab
JSON Object 09.05
625-30m

Lab Summary
You will achieve the following:
• When this lab is complete, you will not only be able to mark a Cloud
Dimensions' Phase II requirement complete, but you will also have the
experience of modifying scripts written by you or by others.
• In this lab, you will add a method to the Script Include you wrote in the
previous lab and then make a copy of the Client Script to re-purpose it.
The Script Include will return a JSON object containing an array of
Group members. The Client Script will dynamically select a group
member from the JSON object to assign to an Incident.

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.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 393
2. Create a Client Script that calls the Script Include method whenever
the value in the Assignment group changes. The name of the randomly
selected analyst is returned from the server, should then populate the
Assigned to field.

A. Prerequisite
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.

B. Add a New Method to an Existing Script Include


1. Open the AssignmentGroupUtils Script Include.

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:

• Add a method to the object called assignAnalyst.


• Store the sys_id of a group from a Client Script in the variable
groupID.
• Create a new array.
• Query the sys_user_grmember table to return records for all
members of the group passed in from a Client Script.
• While there are returned records
• Create a new object to store member information
o Add the sys_id for the member to the new object
o Add the Display Value for the member to the new object
o Push the object into the array
• Return the array of members as a JSON object.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 394
4. Write the highlighted script after the blank lines you inserted in step 2.

5. Select Update.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 395
C. Call the Script Include from a Client Script
1. Open the Lab 9.4 Number of Group Members Client Script.

2. Select Insert and Stay on the form's Context menu to make a copy of
the record and remain on the form.

3. Re-configure the new Client Script trigger:


Name: Lab 9.5 Assign Analyst
Active: Selected (checked)

4. Examine the pseudo-code for the Client Script:


• Create an instance of the GlideAjax object called
AssignmentGroupUtils.
• Add a param to call the assignAnalyst method.
• Add a param to pass the sys_id of the Assignment group value to
the Script Include.
• Use the getXML method and a callback function in your Client
Script to execute the Script Include.
• Pass the response returned from the Script Include to the callback
function
o Locate the answer variable in the returned XML and store the
value in a variable
o Create an object from the JSON formatted string and store it in
the variable members
o Find the length of the array
o If the array has elements
§ Generate a random number between zero and one less than
the number of array elements
§ Set the assigned_to field to the array element selected by the
random number
o Else
§ Clear any value currently in the assigned_to field
§ Generate an alert that says the selected Assignment group
has no members

5. Much of the code for this Client Script already exists from the previous
lab. Using the image on the next page as a guide, make the following
modifications:

a) Modify the statement calling the method name call the


assignAnalyst method.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 396
b) In the callback function, immediately after the var myObj =
response.responseXML… statement

i. Delete the alert(myObj); statement.

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.

D. Test Your Work


1. Open any Incident record.

2. Examine the value of the Assigned to field. Record the value here:
___________________

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 397
3. Change the value in the Assignment group field.

4. Was the Assigned to field populated with the name of an Assignee


from that group? If not, debug and re-test.

5. Record the name of the analyst currently in the Assigned to field here:
_______________

6. Change the value in the Assignment group field to IT Securities. (The IT


Securities group has no members baseline.)

7. Did the value in the Assigned to field clear? If not, debug and re-test.

8. Did an alert advise there are no members in this group? If not, debug
and re-test.

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

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 398
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 funcDon defined in an SNC Script Include, copy that funcDon to the paired version
of the Script Include that does NOT contain SNC. Paste and customize the funcDon there.

It is considered best pracDce to refer to States in your scripts using constants


current.state.changesTo(IncidentState.CLOSED) rather than values
current.state.changesTo(7).

State Models currently exist for the Incident and Change applicaDons. Visit
docs.servicenow.com and search for the following arDcles for more informaDon 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

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 399
As you learned in previous modules, GlideRecord and g_form.getReference() are also available for
retrieving server informaDon. They have a slightly higher performance impact. Both methods
retrieve all fields in the requested GlideRecord when most cases only require one field.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 400
Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 401
Use the Accessible from field to make a Script Include accessible from all scopes.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 402
ProtecDon Policy opDons include:
None – Script Include logic is viewable and editable by anyone.
Read-only – Script Include logic is viewable but not editable.
Protected – Script Include logic is not viewable.

ProtecDon policies do not prevent other developers on the applicaDon development instance from
viewing or ediDng a Script Include.

ProtecDon policies are not applied when applicaDons are published and migrated to an instance
using an Update Set.

For the instance on which an applicaDon is developed, use Access Controls and/or roles to restrict
User ability to see and edit Script Includes. ProtecDon policies do not apply in this case.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 403
Every custom applicaDon has an applicaDon scope that is defined by its namespace.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 404
In the example on the leO, two Script Includes are developed for the Travel Management
applicaDon.
• VendorU,ls – methods for managing vendors and is set to be accessible from all applicaDon
scopes.
• ExpenseU,ls – 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
applicaDon:
• The Business Rule script instanDates the VendorUTls Script Include in the Travel Management
scope to access its confirmVendor method. As this Script Includes' Accessible from value is set
to All applica,on scopes, the Business Rule is permiPed 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 instanDates the
ExpenseUTls Script Include to access its submitExpense method. As this Script Includes'
Accessible from value is set to This applica,on scope only, access is denied.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 405
Lab 9.4 fulfills requirement 8.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 406
Good PracDces

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 407
Discuss: Why, when, and how oOen would you use the capabiliDes shown in this module.

Script Includes
© 2018 ServiceNow, Inc. All Rights Reserved 408
UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 409
In this module you will prac4ce wri4ng, tes4ng, and debugging UI Ac4ons.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 410
UI Ac4ons put bu;ons, links, and context menu items on forms and lists making the UI more
interac4ve, customizable, specific to user ac4vi4es, and applicable to business requirements. Scripts
take ac4on when bu;ons, links, or context menu items are selected.

To prevent a bu;on from appearing at the bo;om of a form, set the glide.ui.bu)ons_bo)om
system property to false.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 411
UI Ac4ons for a list.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 412
If there are too many mobile form bu;ons to fit across a single row in the mobile interface a single
bu;on called Ac4ons appears. Select the Ac4ons bu;on to choose a mobile UI Ac4on.

To create a mobile UI Ac4on open System Mobile UI > UI Ac;ons – Mobile.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 413
Add UI ac4ons to forms and lists in the same scope, as well as to forms and lists that allow UI
Ac4ons from another scope to run on them.

Be cau4ous about modifying baseline records. Save a copy and modify the copy rather than the
original. If you modify a baseline record in any way, that record will not be automa4cally updated in
future ServiceNow updates.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 414
Name – the text that appears on the widget.
Table – table for which the UI Ac4on applies. Global is for all tables.
Order – the order of display of the UI Ac4on. Lower numbers are higher on the list/farthest to the
leK.
Ac;on name – name by which this UI Ac4on can be called in a script.
Ac;ve - select this op4on to enable the UI Ac4on.
Show insert/update – displays the widget on new records/exis4ng records.
Client – UI Ac4on executes in the browser.
List v2 Compa;ble - Specifies that the UI ac4on is can be used with v2 lists and will display on v2
List.
List v3 Compa;ble - Specifies that the UI ac4on is can be used with v3 lists and will display on v3
List.
Applica;on – the scope containing the UI Ac4on.
Form bu)on/context menu/link – if selected enables the widget on a form.
List bo)om bu)on/banner bu)on/context menu/choice/link – if selected enables the widget on a
list form.
Show mul;ple update – (does not appear baseline and must be added through personaliza4on):
Select this op4on to display the widget on mul4ple record update forms.
Show query – (does not appear baseline and must be added through personaliza4on): Select this
op4on to display the widget on Search forms.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 415
Comments – documenta4on about what a UI Ac4on does, who wrote it etc.
Hint – text that appears when a user hovers over the widget.
Onclick – func4on to call when widget is selected.
Condi;on – restricts when a UI Ac4on applies. Has access to current.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 416
If the condi4on field has no value, the script will execute whenever the trigger criteria is met.

The example shown works with a condi4on to offer a user the opportunity to launch the RIM Tech
Support web site in a new browser window if an Incident's CI is Blackberry (see preceding slides for
trigger and condi4on).

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 417
Protec4on policies are not applied when applica4ons are published and migrated to an instance
using an Update Set.

The Protec4on Policy op4ons are:


None – UI Ac4on logic is viewable and editable.
Read-only – UI Ac4on logic is viewable but not editable.
Protected – UI Ac4on logic is not viewable.

For the instance on which an applica4on is developed, use Access Controls and/or roles to restrict
User ability to see and edit UI Ac4ons. Protec4on policies do not apply in this case.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 418
For example, a Close Incident bu;on might be available only to group managers or should appear
only on Incident forms if the state is resolved.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 419
If the Condi4on field has no value the script will execute whenever the trigger criteria is met.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 420
Use client-side methods when scrip4ng for execu4on within the browser. The script has no access
to server-side objects, such as current, or methods, such as gs.log.

Common uses for client-side UI Ac4ons are:


- Show workflow
- Launch email client
- Print preview
- Redirect to another URL

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 421
Only UI Ac4ons included on a form can be called. For example, the Edit Homepage UI Ac4on's link
does not appear on the Incident form and could not be called from a UI Ac4on for the Incident
form.

The gsKSubmit() method can also be called as follows:

gsKSubmit(null,g_form.getFormElement(),'<UI Ac4on Ac4on Name>');

The first parameter is the control (will have the value null when calling UI Ac4ons), the second is the
form, and the third is ac4on name.

For example, gsKSubmit(null,g_form.getFormElement(),'sysverb_insert');

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 422
UI Ac4ons run on the server-side when the Client op4on is not selected.

Use server-side UI Ac4ons when:


• You do not need access to the form.
• You want improved performance.
• You do not need to call client-side UI Ac4ons.
• You do not need access to form elements.
• You do not access to server-side methods.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 423
When the UI Ac4on is called a second 4me the Onclick func4on will not execute because the
bu;on/link/menu item was not physically selected a second 4me. Any code not enclosed in a
func4on is executed. In this case, the if(typeof window == 'undefined') statement runs and the
server-side func4on is called.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 424
Module Labs

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 425
Lab
Client UI Action – 10.01
Priority 1 Incident 615-20m

Lab Summary
You will achieve the following:
• In this lab, you will 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.

2. Create a new UI Action.

3. Configure the UI Action trigger.


Name: Priority 1
Table: Incident [incident]
Active: Selected (checked)
Show insert: Selected (checked)
Show update: Not Selected (unchecked)
Client: Selected (checked)
Application: Global
Form button: Selected (checked)
Onclick: confirmPriOne();
Condition: current.canCreate() && current.isNewRecord()

4. Here is the pseudo-code for the script:


• Get the priority from the Incident form field.
• If the priority is not 1, insert the record into the database.
• If the priority is 1 display a JavaScript confirmation dialog asking if
the user really wants to submit the Incident with this priority.
o If the answer is OK, insert the record into the database.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 426
5. Write the UI Action script:

6. Save the UI Action.

B. Testing
1. Create a new Incident.

2. Set the Priority to Critical by setting the Urgency and Impact fields
each to High.

3. Select the Priority 1 form button.

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.

7. Select the Priority 1 button.

8. Select the Cancel button in the confirmation dialog box. Was the
Incident submitted?

9. Make the Priority 1 UI Action inactive.

Lab Completion
Congratulations on completing the lab!

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 427
Lab
Server UI Action – 10.02
URL Redirect 615-20m

Lab Summary
You will achieve the following:
• In this lab, you will 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.

2. Configure the UI Action trigger.

Name: Check User Info


Table: Incident [incident]
Active: Selected (checked)
Show insert: Selected (checked)
Show update: Selected (checked)
Application: Global
Form button: Selected (checked)
Form link: Selected (checked)
Condition: current.canCreate()

3. Examine the pseudo-code for the script:


• Add/modify the record in the database.
• Try:
o Save the user page URL in a variable.
o Redirect to the URL+the caller's sys_id.
o When finished with the user form return to the current Incident
form.
• Catch:
o Log any errors to the Script Log Statements.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 428
4. Write the UI Action script:

5. Save (not Submit) the 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.

8. Select the Save button.

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.

___________________________________________________________________

___________________________________________________________________

3. Navigate to Self-Service > Incidents, select the New button.

4. In the Incident form, set the Caller to Olga Yarovenko.

5. Select the Check User Info button or link.

6. Did Olga's user record open? If not, debug and re-test.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 429
7. Change Olga's title:

a) Select the light bulb next to the Title field.

b) Select Sales Executive from the suggestions list.

8. Select the Update button to update the User record.

9. What page loads after the User record is updated? Is it the User list
page? Why or why not? Explain your reasoning.

___________________________________________________________________

___________________________________________________________________

10. Make the Check User Info UI Action inactive.

Lab Completion
Congratulations on completing the Server UI Action – URL Redirect lab!

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 430
Lab
Client and Server UI Action – 10.03
Update Problem 615-20m

Lab Summary
You will achieve the following:
• In this lab, you will create a UI Action that executes on both the client
and server-sides. The UI Action will retrieve the problem_id from an
Incident and update the related Problem’s Work notes.

A. Creating a UI Action
1. Create a new UI Action.

2. Configure the UI Action trigger.


Name: Update Problem
Table: Incident [incident]
Action name: update_problem
Active: Selected (checked)
Show update: Selected (checked)
Client: Selected (checked)
Application: Global
Form button: Selected (checked)
Onclick: updateProblem();
Condition: current.canCreate()

3. Examine the pseudo-code for the script:


• In the client-side function
• Try:
o If the Incident form does not have a value in the Parent field
§ Alert the user using the strategy of your choice
o Else
§ Execute the UI Action a second time
• Catch:
o Log any errors to the JavaScript log
• Check the Client Script has completed
• Call the server-side function

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 431
• In the server-side function
• Try:
o Create the string you will put in the Work notes
o Create a new GlideRecord for the problem table
o Get the Parent (Problem Record) for the current Incident
o Add a Work note to the Problem record
o Update the Problem record
• Catch:
o Log any errors to the Script Log Statements

4. Write the UI Action script. If needed, refer to the "Client and Server UI
Actions" slide’s stub code.

5. Save the UI Action.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 432
B. Testing
1. Create or Open an Incident.

2. Located the Related Records Tab and Assign a Problem to the


Problem ID field. Note the Problem number here:

________________________________

3. Select the Update Problem button.

4. Open the Problem you select in step 2.

5. Examine the Problem’s Activity history. Does your message appear in


the history? If not, debug and re-test.

6. Make the Update Problem UI Action inactive.

Lab Completion
Congratulations on completing the lab!

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 433
UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 434
Discuss: Why, when, and how oKen would you use the capabili4es shown in this module.

UI Actions
© 2018 ServiceNow, Inc. All Rights Reserved 435
© 2018 ServiceNow, Inc. All Rights Reserved 436
Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 437
Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 438
Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 439
Flow Designer and Workflow can be used at the same 8me in an instance. Understand 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 s8ll be able to accomplish a task using Flow Designer or Workflow.
Flow Designer
Service Catalog Ac8on 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 crea8on 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 intui8ve 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
Integra8onHub
• Slack, Teams, Ac8ve Directory, Azure AD, and more… (More integra8ons in the future.)
Ac8on Designer – alterna8ve 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

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 440
Flow Designer is a Now PlaSorm feature that enables rich process automa8on capabili8es in a
consolidated design environment. It enables process owners to use natural language to automate
approvals, tasks, no8fica8ons, and record opera8ons without having to code.

IMPORTANT
Permission to use Flow Designer and view flow execu8on 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 opera8ons which is equal to an
admin role.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 441
The welcome page has links to Flows, Subflows, Ac8ons, Flow Execu8ons, Help, and New.

• A Flow is an automated process consis8ng of a sequence of ac8ons and a trigger. Flows


automate business logic for a par8cular applica8on or process.
• A Subflow is a sequence of reusable ac8ons that can be started from a flow, subflow, or script.
• An Ac=on is a reusable opera8on that enables process analysts to automate Now
PlaSorm features without having to write code.
• Flow execu=on is a list of associated execu8on detail pages. Each record is created when a flow
runs. Process analysts can view the informa8on the system stores about the configura8on and
run8me values produced.
• The Help tab has resource links to Documenta8on, Videos, and Community Discussion.
• The New link use a dropdown to allow you to create a New Flow, New Subflow, or New Ac8on.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 442
This example shows the Flow Editor aYer a Flow has been selected.
• House Icon - returns you to the Landing page.
• Flow Tabs – allows you to work on If you have mul8ple flows open, you can select the that you
want to open and work on.
• Plus Icon – selec8ng the icon will allow you to create a new Flow, Subflow, or Ac8on
• Indicator – The text will tell you if you are working on Flow, Subflow, or Ac8on and if the
component of a flow is read only. Flows will have a gray (inac8ve) or green (ac8ve) dot.
• Title – Shows the flow you are currently working on.
• Status – Indicates if the flow is DraY
• Scope – Its encouraged to use flow designer in a scoped applica8on. Since we are
• Proper=es - Edit flow proper8es e.g. descrip8on and protec8on policy
• Test - Simulate a trigger and execute the flow
• Execu=ons - List execu8ons associated with this flow to open opera8ons
• Save - Save a draY of the Flow, Subflow, Ac8on
• Ac=vate - Ac8vate this flow and make the trigger live
• Three Dots icon will open more ac8ons that are specific to the flow, subflow, or ac8on you are
working with
• Trigger - specifies the condi8ons that start the flow. When the trigger condi8on is true, the
system starts the flow.
• Ac=ons – The sec8on 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 ac8on input or
output.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 443
Crea8ng 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.

1. The Trigger dropdown has several Trigger Types to choose from.


• Record Trigger Type - flows start when a record is newly created, updated, or both and if the
transac8on meets the condi8on filter. The Updated Trigger Type can run always or only
once.
• Scheduled Trigger Type starts a flow at specific 8me of the day, week, or month. Also, a flow
can start at a specific 8me and it will Run Once. If you need to set a flow to run at
predefined intervals (example: every 3 days), Use the Repeat choice.
• Applica8on Trigger Type has a MetricBase choice and a Service Catalog choice. MetricBase
will start a flow by tracking 8me series data and can monitor when a threshold is reached,
when a trend is detected, or when a system stops repor8ng data. Service Catalog Trigger
Type monitors all catalog item requests for a specific item.

Unlike a Scheduled and Applica8on Trigger Types, a Record Trigger Type requires:
1. A table to monitor. In this example we have chosen the incident table as the place to look at for
condi8onal changes. Choose the appropriate table.
2. A condi8on that starts the flow. Use the condi8on builder the same way you filter for a list. All
condi8ons created in the condi8on builder must be met.

TIP FROM THE FIELD


You may not be able to use Applica8on Trigger Type. The MetricBase Trigger Type requires
a separate subscrip8on. On the Service Catalog Trigger Type a plugin
(com.glideapp.servicecatalog.flow_designer) will need to be ac8vated. Contact HI
Customer Service system for assistance.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 444
Ac8ons can be anything from crea8ng tasks, looking up records, or sending email. Flow designer
has a number of core ac8ons that can be used and custom ac8ons that can be created.
• A core ac8on is a ServiceNow-provided ac8on available to any flow that cannot be viewed or
edited from the Ac8on Designer design environment.
• Custom ac8ons can be viewed or edited from the Ac8on Designer design environment. The
custom ac8ons always use the same configura8on when added to a flow.

Flow Logic is a way to control what ac8on steps are included or bypassed based or your criteria.
• The If condi8onal statements check if a condi8on is met before execu8ng or skipping an ac8on.
• The For Each Flow Logic loops through a list of records, supplied by flow data, to apply ac8ons for
each record that meets the condi8on specified. Crea8ng a Nested For Each loop requires you to
understand how many flow transac8ons this will generate and its dura8on. Nested For Each
loops are discouraged as they may cause the flow transac8on quota rule to stop a flow aYer an
hour.

Subflows are a sequence of reusable ac8ons 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.

TIP FROM THE FIELD


Flows are set to allow 50 ac8ons or less. You can increase the number of ac8ons with the
sn_flow_designer.max_ac8ons system property., but performance may be impacted. Also,
consider using Subflows for repe88ve tasks used across mul8ple flows.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 445
As you create addi8onal ac8ons, addi8onal Pills will be created. You can use the Pills in Ac8ons,
Flow Logics, and Subflows.

Above, a pill being used with an Ac8on. Below is an example of Pills being used with Flow Logic and
Subflows:

Flow Logic
The Trigger Data Pill is
used in an If condi8onal to
check the trigger incident
record’s priority.

Subflow
The Subflow is using the Pill
from a previous Ac8on as
input. Subflows should be
created for reuse. This
modular design can save
you from crea8ng
repe88ve Ac8ons across
several flows.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 446
Module Labs

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 447
Lab
Build a Flow 11.01
615-20m

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.

A. Build the Flow


1. To open the Flow Designer in a new tab, navigate to the Flow Designer
-> Designer in the Filter Navigator.

2. On the right side of the screen, Select the + New button.

3. From the drop-down, select the New Flow


TIP FROM
option.
THE FIELD:
4. In the Flow Properties window, add the A good practice is to
following information: always create flows
in a scoped
• Name: Incident Changed to P1 application. This will
• Application: Global categorize your
• Description: Monitor Incidents for P1 Activity content and make it
easier to maintain
5. Select Submit and release.
6. After the flow is saved successfully, add a
Trigger by selecting the + Symbol or Click to add a Trigger link.

7. From the Trigger menu, select Created or Updated.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 448
8. Select the Table drop down, type Incident in the search field, and
select the Incident [incident] table.

9. To the right of Condition, select the + Add Filters and set the drop
down to the following:

Priority - is - 1-Critical

10. Select Always on the Run Trigger drop-down.

11. Select Done.

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 the correct Action for your flow.

14. With the ServiceNow Core category highlighted, select the Update
Record Action.

15. Specify the record to update by dragging the pill labeled Incident
Record from the Data -> Trigger – Record Created or Updated section
on the right side of the screen to the Record field in the middle of the
screen.

16. Move down to Fields and select the + Add Field Value button.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 449
17. Set the Select a Field dropdown fields to the following:

Assignment Group – Incident Management

18. Select Done to close the action.

19. Select the blue Save button in the upper right corner.

20. Select the Activate button and Select the OK button when the Confirm
Flow Active dialog box is shown.

B. Test Your Work


You can test the flow with updates to the record that trigger the flow to
execute. However, testing can be done within the Flow Designer.

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 and choose an incident.

3. Select the Run Test button.

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.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 450
6. Review the Execution Details screenshot below and select each link,
indicated by the arrows, in your instance.

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?

_________________________________________________________________

8. Select the on the Execution Details Tab to close it.

9. On the flow, select the to close Test Flow dialog box.

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.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 451
Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 452
A subflow is a container of an 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 plaSorm table, or create approvals with
emails, but they may not be familiar with the details to accomplish thise tasks. By selec8ng a
subflow with mul8ple steps, intensive calcula8ons, or complicated connec8on strings, a process
analyst can quickly take advantage of the power of a subflow and then incorporate it within the
flow they are crea8ng.

Subflows that automate generic business logic that helps process analyst and low code admins to
not only integrate the capabili8es of a Subflow into a flow, but into every addi8onal flow that is
created. The ability to reuse the func8onality over and over in mul8ple applica8ons or processes
increase the speed at which a flow is built and its ease of crea8on..

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 453
Subflows called from a script requirements:

• Create the subflow before you create the script to call it.
• Subflows must be published. Unpublished Subflows will not show up in your ac8ons sec8on and
can not be called from code.
• The script you use must be a server script.
• Use the sn_fd namespace to access the Subflow API.
• Use an asynchronous call. The server script can con8nue execu8ng code and will not have to
wait for the Subflow to finish before moving forward.
• Reference the subflow with the applica8on scope. Calls can s8ll be made to a subflow in the
global scope, but flows should be created within a scoped applica8on.
• Use the Internal name of a subflow. 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 are should be Name-value pairs. If the subflow calls for a reference type value, use a
GlideRecord object as the value.

Can a Flow be called by a script?


Yes. Use the sn_fd and the flow api to access to execute a flow

sn_fd.Flow.startAsync(<unique_scope_name.internalFlowName>, Map inputs)

The Input map keys need to include data that the flow’s record triggers are expec8ng.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 454
Module Labs

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 455
Lab
Trigger a Subflow with a Script 11.02
620-25m

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 that quickly


creates an Incident task record and populate the form.

A. Build the Subflow


1. To open the Flow Designer in a new tab, navigate to the Flow Designer
-> Designer in the Filter Navigator.

2. On the right side of the screen, Select the + New button.

3. From the drop-down, select the New Subflow option.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 456
4. In the Subflow Properties window, add the following information:

• Name: Lab 11.2 Possible 1-Critical Incident


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

6. Under Inputs section, select the symbol.

7. Select the Label Field that is marked variable and change the wording
to number.

8. Select the Type drop down. Choose 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

10. Select Done.

11. Locate the Actions section and select the + Click to add an Action,
Flow Logic, or Subflow.

12. Select Action.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 457
13. Select ServiceNow Core -> Create Task.

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

15. Select Save.

16. Select Publish.

B. Test the Subflow


1. With the Subflow page open, select Test.

2. With the Possible 1-Critical Incident Subflow open, select the Test
button.

3. Add the following values to the Test Subflow dialog box.


• number: Select any Incident from the dropdown
• short_description: Short Description Subflow Test
• description: Description Subflow Test

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 458
4. Select Run Test.

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

9. Select Open Record on the preview incident section.

10. Add the Incident Task related list to the form by selecting
the Additional actions menu button.

11. Select Configure -> Related Lists.

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.

13. Select Save.

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.

C. Build the UI action to call the SubFlow


1. On the Incident form, select the Additional actions menu
button.

2. Select Configure -> UI Actions.

3. Select New.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 459
4. Create a new UI Action.
Name: Create Incident Management Task
Table: Incident [incident]
Active: Selected (checked)
Form Link: Selected (checked)
Show Update: Selected (checked)
Comments: Create Incident Management Task for Review
Condition: current.active;

5. Examine the pseudo-code for the script:

• 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

6. Write the script:

7. Select Submit.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 460
D. Test the UI Action
1. Navigate to the incident you used in your Subflow testing.

2. Select the UI Action Create Incident Management Task Related Link.

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.

4. Was the incident task created? If not, debug and retest.

Lab Completion
Congratulations on completing the lab! You have successfully called a Subflow
from script.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 461
Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 462
The last sec8on in this Flow Designer module is crea8ng an Ac8on. 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 Ac8ons. These roles will use the set of core ac8on steps to
automate Now PlaSorm processes. Also, subject maier experts, scripters, and developers can use
the core ac8on steps to quickly incorporate tedious tasks into a Custom Ac8on. This leaves more
8me to focus on the other challenges of crea8ng 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 8mes component. A key difference between the reuse
of Script Includes and Ac8ons is the accessibility. Script Includes need to be called from code. Flow
Designer interface makes code reuse easier by making the Ac8on easily discoverable. Think about
other departments within you organiza8on u8lize the same Ac8ons you create.

IMPORTANT
The ac8on_designer role is required to build Custom Ac8ons.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 463
Just like the subflow you created in the previous lab, inputs and outputs in an Ac8on func8on the
same way. The Input of an Ac8on allows data, of various types, to pass to the Ac8on Steps. AYer
processing the data, Informa8on is relayed back to the flow. This returning data may be used in
addi8onal subflows or ac8ons.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 464
Just as Flow designer has a number of core ac8ons, several core ac8on steps have been provided to
help with building an ac8on.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 465
Previous modules have stressed the importance that scripts should only be created when a feature
or func8onality is not available in a baseline instance. Ac8on Designers should follow this same
advise when a Script Step is created.

IMPORTANT
The Script step provides the ability to create integra8ons with third party systems, but this
func8onality requires the Integra8onHub plugin to be ac8vated. If you are crea8ng a script
for your instance only, the plugin is not required.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 466
The Javscript steps includes separate Input and Outputs Variables. A Script step Input Variable will
need to be created, named, and an Ac8on Input Variables data pill added to the Value field to make
the Ac8on 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 ac8on. The Script Step Input and Output
Variables can be referenced in the script with the inputs and outputs prefix.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 467
Module Labs

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 468
Lab
Add a Script to a Flow 11.03
620-25m

Lab Summary
You will achieve the following:
• Build a custom action that uses a script step
• Build a flow that includes the custom action

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 be added to the records work notes. Data should be used from the
incident to make a brief summary.

A. Build the Custom Action


1. Navigate to the Flow Designer -> Designer in the Filter Navigator.

2. On the right side of the screen, Select the + New button.

3. From the drop-down, select the New Action option.

4. In the Action Properties window, add the following information:

Name: Lab 11.3 Custom Action Script


Accessible From: All Application Scopes
Application: Global
Description: Create an After Action Report

5. Select Submit.

6. In the Action Input, select the + Create Input.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 469
7. Select variable to change the Label, the drop down to change the
Type, and the + Create Input for new variables to add the following
inputs to the Action Input section.

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

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 470
8. Under the Action Outline, Select the + symbol between the Inputs and
Outputs.

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

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 471
14. Write the script in script field:

15. Under the Action Outline, select the Outputs.

16. Select + Create Output to create an Action Output.


Label: After Action Report
Value: Step-> Script step -> Payload
(Drag the Payload Pill from the Data Panel)

17. Select Save.

18. Select Publish.

B. Create the Flow


1. In the tab section, select the Plus ( ) icon.

2. From the drop-down, select the New Flow option.


Name: Priority 1-Critical Incident Closed
Description: Priority 1- Critical Incident Closed - Create After Action
Report

3. After the flow is saved successfully, select the + Symbol or Click to add
a Trigger.

4. Create an Updated trigger with these conditions:


Table: Incident[incident]
Condition: State - is - Closed and
Priority - is - 1-Critical and
Active - is - false
Run Trigger: Once

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 472
5. Select Done.

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 THE FIELD:
dot-walk to the data for each Action Input.
The Data Pill Picker
Note: To dot-walk to data in the Data Panel, look can be faster than
for the right arrow( )next to the Data Pill. Select the mouse to dot-
the right arrow and data from that table is shown walk to the data you
below the pill. need. Use the arrow
keys and type the
To dot-walk to data in the Data Pill Picker, select
field name for
the location of the data. In this case, it will be the
navigation.
Trigger – Record Updated. Select a right arrow( )
of referenced data. When you have drilled down
to the table, use the search bar to narrow the fields shown.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 473
10. Update the Action Inputs

11. Select Done.

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.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 474
15. Select and drag the Incident Record from the Data Panel to the
Record field.

16. Select the Fields dropdown and choose Work notes.

17. Select and drag the Lab 11.3 Custom Action Script After Action Report
data pill to the Fields value field.

18. Select Done.

19. Select Save.

C. Test Your Work


1. Select the browser tab with the regular ServiceNow interface.

2. Create an Incident record.


Caller: Abel Tuter
Configuration Item: 3D Pinball
Short Description: 3D Pinball is Broken
Impact: 1-HIgh
Urgency: 1-HIgh
Assignment Group: Incident Management
Assigned To: Incident Manager
Resolution Code: Solved (Work Around)
Resolution Notes: Inserted a quarter
Resolved: Pick at least two days in the future.
Resolved By: Beth Anglin

3. Select Save.

4. Return to Flow Designer.

5. On the flow Lab 11.3 P1 Closed, select Test.

6. Use the number from the Incident created in the Record field.

7. Select Run Test.

8. After the flow process completes, open the Execution Details tab with
the Flow has been executed. To view the flow, click here link.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 475
9. Was “work_notes=After Action Report Subject: After Action Report,
Incident Manager – Incident Management…” shown on the Update
Record -> RUNTIME VALUE column? If not Debug and retest.

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

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 476
Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 477
Discuss: Why, when, and how oYen would you use the capabili8es shown in this module.

Flow Designer
© 2018 ServiceNow, Inc. All Rights Reserved 478
© 2018 ServiceNow, Inc. All Rights Reserved 479
www.servicenow.com/services/training-and-certification.html

4810 Eastgate Mall, San Diego, CA 92121, USA • (858) 720-0477 • (858) 720-0479 • www.servicenow.com

©2018 ServiceNow, Inc. All rights reserved.


ServiceNow believes information in this publication is accurate as of its publication date. This publication could include technical inaccuracies or typographical errors. The information is subject to change without
notice. Changes are periodically added to the information herein; these changes will be incorporated in new additions of the publication. ServiceNow may make improvements and/or changes in the product(s)
and/or the program(s) described in this publication at any time. Reproduction of this publication without prior written permission is forbidden. Then information in this publication is provided “as is”. ServiceNow
makes no representations or warranties of any kind, with respect to the information in this publication, and specifically disclaims implied warranties of merchantability or fitness for a particular purpose.
ServiceNow is a trademark of ServiceNow, Inc. All other brands, products, service names, trademarks or registered trademarks are used to identify the products or services of their respective owners.

You might also like