Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
344 views60 pages

50 Assignment Itsm With Solution

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)
344 views60 pages

50 Assignment Itsm With Solution

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/ 60

giveRole();

REQUIREMENT
Calling giveRole function

function giveRole(){

For every hour automatically assign try{


var usergr = new GlideRecord("sys_user");
create usegr GlideRecord object of sys_user table

analytics_admin role for users who don't usergr.query();

have analytics_admin or analytics_viewer query the table using query method with usergr object

role.
while(usergr.next()) {
run while a loop, each time a record is processed with
var urolegr = new GlideRecord("sys_user_has_role"); usegr.next();
urolegr.addQuery("user", usergr.sys_id);
urolegr.addQuery("role.name", "IN", Create another GlideRecord object urolegr of sys_user_has_role
"analytics_admin,analytics_viewer");
table
urolegr.setLimit(1);
urolegr.query(); Add query with addquery method, filter records where role is
analytics admin and analytics viewer
Also the result filter by user sys_id which you can get from usergr
object.
giveRole function

01
in summary, for each user record, provide the user sys_id and
roles names in order to filter in the sys_user_has_role table, and
return the result with urole.query();.

if(!urolegr.next()){

urolegr.initialize();
urolegr.user = usergr.sys_id;
urolegr.setDisplayValue("role", "analytics_admin");
urolegr.insert();
} !urolegr.next() will be true if there isn't a record and will be false if
}
there is a record.
}
The goal is to assign a role to specific users within a time period, write the script which will check the conditions, make sure that all catch(ex){ gs.info(ex);} In case it is true, set values for role field. the role will be
users don't have analytics_admin or analytics_viewer role, use the the script in a scheduled script, scheduled for every hour. } analytics_admin. and insert a new record in the sys_user_has_role
table
REQUIREMENT
Before Business Rule

ServiceNow

Check if the current time is greater than start


date time and smaller than end date time. Time
inbetween A server side code can be executed after the
the form
We assume here start date time and end date
form submission and before the data gets
submission Before Business Rule updated into the database.
and the

time are two Date/Time fields in a form. database


update
This is called a Before Business Rule

Database

02 var now = new GlideDateTime().getNumericValue();

var start = new


GlideDateTime(start_date_time).getNumericValue();

var end = new GlideDateTime(end_


date_time).getNumericValue();
Get the current time with GlideDateTime Object and
getNumericValue method will return the int value of specificed
character and store in now variable

Get the numercial value for start date and end date time, store
in start and end variables

Before Business Rule


if (now > start && now < end){
current.timecheck = 'true';
A before BR can be executed to check if the current date is between start date time and end date time, if it is true, it can }else
update timecheck field to true. Create two date fields in a custom table, then write a before business rule for that table. { Compare if now is bigger start and now smaller than end.
current.timecheck ='false';
}

else condition returns false


if it is true update timecheck field
update time check value to
to true
false
REQUIREMENT

onLoad Client Script

Hide an Icon in the incident form. Servicenow Form

onload script

During the lapse of

03
time when the system Get the HTML element of the icon and store
it in a variable
renders first the form function onLoad() {
and before the access
is given to the user in var icon=document.getElementById("toggleMoreOptions");
order to work with the icon.style.display='none';
form, }
Change css display style to none
onLoad Client Script is
executed Such client
script allows us to
configure forms, forms
field and field values

While the form is loading, onLoad script code will change the css style display value to none of the 3 dotted icon, the html
element id of the icon can be found by using chrome developer tool.

Servicenow rendered Form


var agg = new GlideAggregate('incident');
agg.addAggregate('COUNT', 'assigned_to');
agg.query();
Creating a on Object of from the class
GlideAggregate for incident table,
GlideAggregate is an extension of
GlideRecord. It provides the capability
REQUIREMENT to do aggregation (COUNT, SUM, MIN, Incident table query result 1
MAX, AVG)

And quering the table

Group incidents by assigned to and var arr = []; creating an empty array While loop

list only grouped records where the


Abel Tuter 2
while (agg.next()) {
//do things on the results

assigened to have more than one


var incidentCount = agg.getAggregate('COUNT', 'assigned_to'); Fred Luddy 0

for each count result processed by the Chris Grimes 1

record
system during a while loop, store the
count value in a incidentCount variable

for examples if Abel Tuter have 5


incidents
store 5
if (incidentCount > 1) {

04
// gs.info('Display the count {0}', [incidentCount]);
if incident count >1
var inc = new GlideRecord('incident'); When the incident count is more than
one, create Inc Object of the class
inc.addEncodedQuery('assigned_to=' + agg.assigned_to); GlideRecord for incident table.
Incident table query result 2
inc.query();
add encoded query with agg.assigned.to,
query incident table, here the user have Abel Tuter
more than one record assigned to him INC01
while (inc.next())
arr.push(inc.sys_id.toString()); INC02 Abel Tuter
Test the script in background to see the result }}

return arr; Create another while loop to store all


records sys_id into the empty array. Arr =[inc01_sys_id, inc02_sys_id];

this while loop is inside the previous While loop inside the first while loop
loop.
REQUIREMENT
UI Macro
UI macros are scripted components in servicenow that admins can add to the user interface.

The script is written in between Jelly Tags and the ui macro can be invoked from an ui page, from
another ui macro or by defining specific attributes in a reference field.
Create a Knowledge Base article using
an UI macro See below few examples of ui macros

05 For our requirement, we will have an ui macro created next to the incident reference
field and we will take as inputs data from two other fields (Short Description and
Description) in order to create the knowledge base.
UI macro script and UI macro rendering
<?xml version="1.0" encoding="utf-8" ?>
Jelly
<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide"
xmlns:j2="null" xmlns:g2="null">

Incident reference field Post Knowledge UI macro


Post Knowledge Button Html element

Short Description <button id="button" onclick="kbCreate();">Post


Knowledge</button>
KB create function <script>
Description
.... function kbCreate(){

UI Macro Script Create a GlideRecord Object of kb_knowledge table


....... var gr= new GlideRecord('kb_knowledge');
gr.initialize();
gr.short_description =
Initialize and get short description, description and store in short description, g_form.getValue('incident.short_description');
text field values - text is a database name for artical body field. gr.text=g_form.getValue('incident.description');

gr.insert();
Dictionary Fields list view
}
insert record </script>

</j:jelly>
Incident Reference Incident Attributes

Jelly

Defining an attribute value for the incident


reference field such as
ref_contributions=create_kb will render the ui
macro next to the incident reference field.
New Record in KB Knowledge Table
create_kb is a ui macro name.

The ui macro name is create_kb, which is a database name, mention it in the attributes field,attributes is
a dictionary field of the incident reference field, the ui macro script has the html code to render the
icon, and call a function when the ui macro is clicked,
the function will simply run a query in Kb_Knowledge base, get short description and description from
the form and insert a new record.
REQUIREMENT
Before Business Rule

ServiceNow

Restrict Submission on a incident form


when the description field is empty and Time
inbetween A server side code can be executed after the form

the state field value is 2 or 3. the form


submission Before Business Rule
submission and before the data gets updated into the
database.

and the This is called a Before Business Rule


databse
update

Database

06 (function executeRule(current, previous


/*null when async*/) {

gs.addErrorMessage('Your Message Here');


Before Business Rule

Abort the current action

current.setAbortAction(true);
Before the database gets updated, restrict the form submission if the state of the incident is either 2 or 3, mention the condition in the
})(current, previous);
before business rule and the script to abort the action, this br is written on insert and updates.
REQUIREMENT After Business Rule

Database updated

If a user in his profile has position equal After the


database
update A server side code can be executed

to non-agent , position is a custom field after the data gets updated into the
database.
After Business Rule

in the user table and the user has ITIL This is called a After Business Rule

role, remove ITIL role for the user.

Create myrole object of GlideRecord Class- (function executeRule(current, previous /*null when async*/) {
sys_user_has_role Table // Add your code here

07
var myrole = new GlideRecord('sys_user_has_role');

Add query with the user sys_id and itil role


myrole.addQuery('user', current.sys_id);
myrole.addQuery('role.name', 'itil');
After Business
Rule Script myrole.query();
Query
if(myrole.next()){

myrole.deleteRecord();
}

if there is a record, which means the myrole.next() is


})(current, previous);
This requirement is a verification of field values and action taken based on the value, therefore, write an after business rule, for true
updates and insert. This br will have in condition : postion is equal to non-agent, run a script which will the current user and verify delete the record
if the user has ITIL role, if yes it will remove the role by deleting the record.
REQUIREMENT

After Business Rule

If a user in his profile has position equal Database updated

to agent , position is a custom field in the After the


database

user table, add ITIL role to the user. update A server side code can be executed
after the data gets updated into the
database.
After Business Rule
This is called a After Business Rule

08
Create myrole object of GlideRecord Class-
sys_user_has_role Table (function executeRule(current, previous /*null when async*/) {

var role = new GlideRecord('sys_user_has_role');


Get the current user sys id assign the value the user role.initialize();
After Business
field, also assgin the itil sys_id to the role field, role.user = current.sys_id;
Rule Script
role.role= "282bf1fac6112285017366cb5f867469";
role.insert();
})(current, previous);
Insert a record

This requirement is a verification of field values and action taken based on the value, therefore, write an after business rule, for
updates and insert. This br will have in condition : postion is equal to agent, run a script which will get the current user and add itil
role.
REQUIREMENT

Send a notification to the assigned to of an


incident , whenever a custom date field is Script and Diagrams for this
requirement
Notification

superieur than the current date time. 1 Create grInc a Glide record Object of Incident table

Notifcation is sent when

trigger.notification event is fired

var grInc = new GlideRecord('incident');


grInc.addActiveQuery();
grInc.query(); 2 grInc Active Query

query
while(grInc.next()){

09
if(new GlideDateTime(gr.reached_date).getNumericValue() >= new
GlideDateTime().getNumericValue()){ While loop

gs.eventQueue('trigger.notification',grInc,grInc.assigned_to.toString()); 3
}}

compare the current time compare the current time compare the current time
and the reached time in and the reached time in and the reached time in
numerical value numerical value.... numerical value....

Event Registry
4
queue an event and notifiy queue an event and notifiy queue an event and notifiy
the assigned to ... ...
trigger.notification

Regiser an trigger.notification event for the incident table, create as well a beta notification triggerd
when the event is fire, then write a scheduled script to query the incident table for meeting the
condition above, if there are records overdue 30, 60, 90 days , generate overdue reminder from the
script, which will automaticatlly send the notifications.
Script and Diagrams for this
Notification requirement

Create grInc object of GlideRecord Class- incident Table

Notifcation is sent when

trigger.notification event is fired var grInc = new GlideRecord('incident');


grInc.addActiveQuery();
grInc.query(); Query the table to find all active records

while(grInc.next()){

if(new GlideDateTime(gr.reached_date).getNumericValue() >= new GlideDateTime().getNumericValue()){ While the system process in each record, compare the
numerical value of the current time to the reached_date
gs.eventQueue('trigger.notification',grInc,grInc.assigned_to.toString()); time, reached is a custom date field, if the reached_date is
}} bigger than the current time, queue an event
gs.eventQueue, trigger.notification event is created in the
event registry, as a parameter mention the assigned_to
string value.

Event Registry

trigger.notification
Tables and Data Import Process Key Information

REQUIREMENT
On the first load, the data source will create a staging table and load data into it. An
import set will be also created.
1 Data Source Excel ISET Record will contain info about the data load, data source, rows etc
Staging table will have the data, fields will start u_ for their database name which will
facilitate to auto map matching fields during transform map.
Staging table is a child table of an import set row table.

There is an import set with 2 columns 2 Staging Table Import set Row Table
There are many ways to import data, example xls, script.

u_asset_name and u_updated_asset_name example


Surface Pro and Surface Pro 16. Update the display
name field value in the alm_asset target table with 4 Get incoming Asset and newAsset name from source table (function runTransformScript(source, map, log, target) {
On Before Transform
Map Script // Add your code here
incoming asset newAsset Name
var incomingAsset = source.u_asset_name;

the updated asset name value. var newAssetName = source.u_updated_asset_name; /

var grAlm = new GlideRecord("alm_asset");


Create grAlm Object of GlideRecord Class -
3 alm_asset table

Transform Map

10
OnBefore grAlm.addQuery("display_name", incomingAsset);
Transform Adding query with incoming asset name and query grAlm.query();
Map Script

if( grAlm.next())==false if( grAlm.next())


if (grAlm.next()) {
if there is a record
if there is no record
with incoming
with incoming asset
asset name
name

Target Table :
alm_asset grAlm.setValue('display_name', newAssetName);
set value of newAsset Name grAlm.update();
log info asset not found variable to the name field ( log.info('Asset updated');
display_name ) }
else{
log.info('Asset not found->' + incomingAsset);
For this exercise, create an excel file sheet with some dummy data, the file should have two columns : asset name and updated asset name, for
}
asset name, use the names values available in the asset table and for updated asset name, put some text as per your wish. Create the ignore = true;
datasource, run it to have a staging table with some data, then create a transform to map data in between staging table and target table, write
the onbefore transform script to get data from staging table, then use the incoming asset name to find records in alm asset table with similar
})(source, map, log, target);
names, it there is such records, update then nw values with updated newAssetname
REQUIREMENT onChange Client Script

Yellow
ServiceNow

In problem record, hide the Notes section When a user or systems changes the value
of a field, we can run onChange client
when state is equal to '102'. When user
script.
or system
onChange Client script The script is written on a specific field.
changes a
field value
The client script is excuted once the
change is occured.

Blue
ServiceNow

11
when the state field will get a new value or current value is 102 onChange script can be called
to hide the notes tab

On load

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


if (isLoading) { Get the state value and if it is equal to 102 ,
if(g_form.getValue('state') == '102'){
change the display value to false for notes
g_form.setSectionDisplay('notes', false);
}
return;
} Onchange
client
if (newValue == "102") { script On Change
g_form.setSectionDisplay('notes', false);
The onchange client script will if there is a new value for state field, here if the database value is equal to 102, it wil } else {
g_form.setSectionDisplay('notes', true);
hide the note changing section display value to false, this client script will also check the state value while the form is } if the new state value is to 102 , change the
loading. } display value to true for notes
REQUIREMENT Display Business Rule

Database Server
System is During the lapse of time when the

In the Incident form make the contact type loading


and
system renders first the form and
before the access is given to the user
g_scratchpad

rendering in order to work with the form, a


field editable only for Assignment group the form server side script can be executed,
this is a called a Display Business

members. Display Business Rule Rule.

A Display Business
onLoad Client Script Passing the Rule can instantiate
scratchpad g_scratchpad object
object to the which can be passed
Yellow
ServiceNow client side to the client side and
it can be used in

12
client script.

Client
When user
During the lapse of time when the system
or system renders first the form and before the
onload Client script
changes a access is given to the user in order to g_scratchpad
field value work with the form, onLoad Client Script
is executed

Such client script allows us to configure


forms, forms field and field values
Yellow
ServiceNow

For this requirement use a scratchpad object which will have a boolean value either true or false, if the current user is
not member of that particular assignment group it will be false, based on the scratchpad value, modify field attributes.
write a display Business Rule on Insert and update, which will have a scratchpad object, the value it will be true if the
logged in user is member of the assignement group, use the scratchpad on the client side, if the value is false, meaning
the user is not member then you set the field read only, the opposite condition will let the user access the field.
Display Business Rule

Server
Database

System is During the lapse of time when the


loading system renders first the form and
g_scratchpad
and before the access is given to the user
(function executeRule(current, previous /*null when
async*/) { rendering in order to work with the form, a
Create a Display Business Rule for the incident table,
1 use the script which checks if the current user is part
the form server side script can be executed,
g_scratchpad.isMember = this is a called a Display Business
gs.getUser().isMemberOf(current.assignment_group.toStr the assignment group and stores the value in a Rule.
ing()); scratchpad object g_scratchpad.isMember Display Business Rule

})(current, previous);

A Display Business
onLoad Client Script Rule can instantiate
Passing the
scratchpad g_scratchpad object
object to the which can be passed to
Yellow
ServiceNow client side the client side and it
can be used in client
script.

When user
or system Client
changes a
field value During the lapse of time when the system
onload Client script renders first the form and before the
function onLoad(){ Create a onLoad Client script on the incident table access is given to the user in order to g_scratchpad
use the scratchpad object in a onload client script work with the form, onLoad Client Script
if(g_scratchpad.isMember.toString() == 'false'){ 2 if the value is false, meaning the user is not part of is executed
g_form.setReadOnly('contact_type', true);
// add few more fields as per your requirement the group, make the contact type read only with
} setReadOnly method Such client script allows us to configure
forms, forms field and field values
Yellow
} ServiceNow
REQUIREMENT

Add 30 seconds to the current date/time and We can create a UI action to provide any of these controls:

A button on a form.
set this value to a custom date time field from A context menu item on a form that appears when you open the form context menu or right-click the form header.
A related link in a form.

an UI Action. A button in the banner on top of a list.


A button at the bottom of a list.
A context menu item on a list that appears when you open the list context menu or right-click the list header.
A menu item for the action choice list at the bottom of a list.
A related link at the bottom of a list.

Getting the current time

13
Adding 30 seconds to the current time

var gdt = new GlideDateTime();

gdt.addSecondsUTC(30); UI Action Script

current.published_date= gdt; Setting the new value to published date field

current.update();

action.setRedirectURL(current);

Updating and redirect to the record page

create an ui action, it will have a script which will get the current time, add 30 seconds and then the new value to the
custom date field, the script is called whenever you click on the ui action.
REQUIREMENT

The property values of Previous object The property values of the Current
are the values for the record fields Object are the values as they exist in
when they were loaded from the the runtime environment.
The user should select only the Stage in database and before any changes
were made.

the below order, It's basically a drop-


previous.stage current.stage
down menu where a user is allowed to
Changing from WIP or

update values in a defined order. WIP Resolved or Closed to


Assigned

Resolved Assigned
This is the order : ->Start->Assigned->WIP->Resolved->Closed For Ex: the
user cannot select WIP before choosing Assigned as previous value for the drop Closed
down menu, he/she cannot select resolved as value before choosing wip as
previous value.
The change that you can see above can be translated in if(current.stage == 'assigned' && previous.stage != 'start'){
programming with the follwowing code current.stage == gs.addErrorMessage('You are allowed to change stage from
'assigned' && previous.stage != 'start', start being one of Start to Assigned only');

14
the stages. current.setAbortAction(true);

If the condition is true we do not allow user to submit the


form,
with the following code current.setAbortAction(true);

We replicate this logic for all the rest possible current


stages such as WIP, Resolved and Closed

Remember that start should not consider for the current


stage, because theoricaly there is no stage before start,
therefore we have only 4 condition to establish or test.
Before Business Rule
previous.stage current.stage

Changing from WIP or


if(current.stage == 'assigned' &&
WIP Resolved or Closed to previous.stage != 'start'){ ServiceNow
Assigned
gs.addErrorMessage('You are allowed to
Resolved Assigned change stage from Start to Assigned
only');
Closed current.setAbortAction(true);
Time A server side code can be executed after the form
inbetween submission and before the data gets updated into the
the form database.
previous.stage current.stage
submission Before Business Rule
if(current.stage == 'wip' && previous.stage This is called a Before Business Rule
Changing from Assigned and the
Assigned or Resolved or Closed to != 'assigned'){ databse
WIP
gs.addErrorMessage('You are allowed to For this requirement, write a Before
update
Business Rule with the following condition
Resolved WIP change stage from Assigned to WIP only');
description is empty and state is either 2 or
current.setAbortAction(true); 3.
Closed } Add state is one of in Progress and on Hold
Database for filter conditions.

previous.stage current.stage

Changing from Assigned if(current.stage == 'resolved' &&


Assigned or WIP or Closed to
previous.stage != 'wip'){
Resolved In this code we check four conditions, for example if the
gs.addErrorMessage('You are allowed to
WIP Resolved
current stage is assigned and the previous stage is different
change stage from WIP to Resolve only'); than start, BR will abort the submission, the same logic is
current.setAbortAction(true); applied to allow changes only from start to assigned or
Closed } assigned to wip or wip to resolved or resolved to closed.

previous.stage current.stage

Changing from Assigned if(current.stage == 'closed' && previous.stage


For this requirement, Create a before business rule on the
Assigned or Resolved or WIP to
!= 'resolved'){
Closed incident table and on update, with the filter condition
gs.addErrorMessage('You are allowed to
states changes.
Resolved Closed change stage from Resolve to Closed only');
current.setAbortAction(true);
WIP }
REQUIREMENT onLoad Client Script

While the form is loading, onLoad script code will change


the css style display value to none of the 3 dotted icon, the
Servicenow Form html element id of the icon can be found by using chrome

Get the current date time using a client developer tool.

script.
onload script

During the lapse of time


when the system renders Get today's date with the new Date();
first the form and before javascript method
the access is given to the
user in order to work with
var today_date = new Date();
the form, var today_date_time = formatDate(today_date,
g_user_date_time_format);

15
onLoad Client Script is alert(today_date_time);
executed Such client script Format the date similar to the current
allows us to configure user's date format
forms, forms field and field
values

Alert the time in the browser

Get the current date time using a client script, format the date and alert it

Servicenow rendered Form


Sys_email Table
REQUIREMENT

Sys_id ... ...

515dfef .. ...

Create an incident through an inbound


1 When the inbound email is triggered, it creates a record in sys_email table to validate

email action, the incident short the creation of email. Get the sys_id.

description should be same as the


attachment file name. Attachement table

File name Table Name sys_id

16
script.pdf sys_email 515dfef

Sequence of events
2 query the attachment table with sys_email sys_id, if there is a record, we can retrieve the pdf file name.
use the pdf file name and set it as value in for short description field notice it is not sys-email
but incident table for the
same record in the
attachement table

State of the Attachement table once the pdf file is attached to incident record

File name Table Name sys_id

script.pdf Incident 545fdsd


(function runAction( current, event, email,logger,classifier) {
sys_email.sys_id contains the sys id of sys_email record,
store it in a test variable and create attachementName an
empty variable var attachmentName = '';
var test = sys_email.sys_id;

var grAtt = new GlideRecord('sys_attachment');


Creating grAtt Object GlideRecord Class - sys_attachement table grAtt.addQuery('table_name','sys_email');
grAtt.addQuery('table_sys_id',test);

grAtt.query();
Adding and Querying the table with sys_id and table name

Inbound Email Script

if there is a record , meaning gr.next()==true if(grAtt.next()){


store the file name in attachment name locale variable attachmentName = grAtt.file_name;
}

current.caller_id = "Abel Tuter";


current.short_description = attachmentName;
current.comments = "received from: " + email.origemail + "\n\n" +
Defining values caller id , comments and notice for
email.body_text;
short_description we use attachmentName variable, we then
insert a new record. current.insert();
})(current, event, email, logger, classifier);

Create an inbound email action for the incident table, with the
action type record action.
REQUIREMENT

Database updated
Change the short description of a
problem ticket 30 minutes before a time A server side code can be executed
after the data gets updated into the
database.

set in a custom date/time field. After the


database
After Business Rule This is called a After Business Rule

update

get the time from the custom field


retrieve the event input which is the record sys id
var taskSysId = event.parm1;

Add -1800 var grPro= new GlideRecord("problem");


grPro.addQuery("sys_id", taskSysId);
grPro.query();

17
create grPro Object of GlideRecord Class - problem table
if ( grPro.next()) {
grPro.short_description = test;
Generate Queued Event
grPro.update();
Script Action
}

query with the input

if there is a record, update the short


description with a value
(function executeRule(current, previous /*null when async*/) {

var gdt = new GlideDateTime(current.dateTimeField);


gdt.addSeconds(-1800); // 30 mins is 1800 seconds
We can do this by writing a script action which will respond to an scheduled event, and the scheduled event is
gs.eventQueueScheduled("your_event_name", current , current.sys_id,'',gdt);
created in a after business rule, the rule will get the time from the custom field and substract 30 minutes, the event
will be scheduled for that specific time.
})(current, previous);
REQUIREMENT

Turn off notifications to all users with a


script. Creating rec objec of GlideRecored class - sys_user table
var rec = new GlideRecord('sys_user');

Disable rec.query();
Notification Script Querying the table

rec.setValue('notification', 1);
rec.updateMultiple();
Setting disable as value for notification field and

18
update in all records

Write a scheduled script or background script to test this requirement

A simple script to query the sys_user table and change the notification field value to 1 and update the new value.,
REQUIREMENT

UI Action visible only when the logged in GlideUserHasRecords Script Include

user is an admin, and has more than 5


incident records where he/she is a caller. var GlideUserHasRecords= Class.create();
GlideUserHasRecords.prototype = {
initialize: function() {
}, Create grInc object of GlideRecord Class - Incident table

checkCondition: function(){
Filtering the table where caller id is the current user id and quering

var grInc= new GlideRecord("incident");


grInc.addQuery("caller_id", gs.getUserID()); checkCondition(); Method
grInc.query();

19
if(grInc.getRowCount() > 5)
return true;
else
if conditon
return false;
there is more than 5 records there is not more than 5 records
}, return true return false

type: 'GlideUserHasRecords'
};

Create an UI Action for incident table, give it a name you want and use this line as condition
gs.hasRole('admin'&&)new GlideUserHasRecords.checkCondition();

The script include and its method will run a query in the incident table, looking for records where the loggedin is
assigned to, if there are more 5 records, it will return true , the ui action will be then visible.

The condition field in the ui action have the code line to check if the user is an admin.
REQUIREMENT

Send overdue 30, 60 and 90 days reminder


to the assigned user.
sendEmail();
Calling sendEmail function

Overdue Reminder Notification

function sendEmail(){ 2 gr is a GlideRecord Object of incident Table

try{
var gr = new GlideRecord('incident');

Notifcation is sent when gr.query();

Overdue.Reminder30 Event is fired while(gr.next()){ 3 gr.query();

var gdt = new GlideDateTime(gr.sys_created_on);


var nowTime = new GlideDateTime();
Incident 2

20
Incident 1 Incident 3

var duration = GlideDateTime.subtract(gdt, nowTime);


var days = duration.getDayPart();
4
if(days == 30 || days == 60 || days == 90){

gs.eventQueue("Overdue.Reminder30", gr, gr.assigned_to);


sendEmail function
5
Get the current time and Get the current time and Get the current time and
record created time, record created time, record created time,
substract current-now substract....
} substract....

}
}
catch(ex){
Event Registry
}
gs.info('Exception'+ex);
6
if days are equal to 30 or 60 or 90

}
Overudue.Reminder30

7
queue a overdue reminder

Regiser an Overdue.Remider30 event for the incirent table, create as well a beta notification triggerd
when the event is fire, then write a scheduled script to query the incident table for meeting the
condition above, if there are records overdue 30, 60, 90 days , genearte overdue reminder from the
script, which wll automaticatlly send the notifications.
sendEmail();
Calling sendEmail
function

Overdue Reminder Notification

function sendEmail(){ Create a grInc object of GlideRecord Class - Incident table


try{
var grInc = new GlideRecord('incident');

Notifcation is sent when grInc.query();


Run a query with grInc.query(); method
Overdue.Reminder30 Event is fired while(grInc.next()){
var gdt = new GlideDateTime(grInc.sys_created_on);
var nowTime = new GlideDateTime();

var duration = GlideDateTime.subtract(gdt, nowTime);


var days = duration.getDayPart(); For each record the system process in a while loop, get the
created date , store in gdt variable, define the current time
substract the gdt with current time,store it in duration
if(days == 30 || days == 60 || days == 90){ variable.
sendEmail function With getDayPart method get only the days
gs.eventQueue("Overdue.Reminder30", grInc, grInc.assigned_to);

}
}
}
catch(ex){
Event Registry gs.info('Exception'+ex); if days are equal to 30 or 60 or 90
}
}
Overudue.Reminder30

queue a overdue reminder event, the event is


already created in the event registry
REQUIREMENT create a new string type field for the table you want, make it
a function field

Add the form sys_id to the form Table Incident Active

Type String Function Field

Column label Primary Identifier (PIN)

Column name u_primary_identifier

Function Definition
glidefunction:concat(sys_id)

21 add the follwing line glidefunction:concat(sys_id) to the


function definition field
REQUIREMENT

onLoad Client Script

Alert the caller id while loading the incident Servicenow Form

form
onload script

During the lapse of time


1 get the caller id and test if it is true

22
when the system renders
first the form and before
the access is given to the function onLoad(){
user in order to work with
the form,
2 create name variable, store the value
if(g_form.getValue('caller_id')){
var name = g_form.getDisplayBox('caller_id').value;
onLoad Client Script is alert(name);
executed Such client script }
allows us to configure
forms, forms field and field
values 3 alert the name
}

Simple client to get the caller id and alert it, this is onload client script

Servicenow rendered Form


REQUIREMENT

Download all incidents record with an UI


Get the sys id of form and store it in a
sysId variable

Action function downloadRecords(){


var sysId = g_form.getUniqueValue();
var query = 'incident=' + sysId :
create query variable to store sysid
UI Action Client Script and the string 'incident' into table var table = 'incident';
variable g_navigation.open('/' + table + '_list.do?
XLSX&sysparm_query=' + query, '_blank');

23
use g_navigation.open to call a url with the
table and query as parameteres

Construct an url with a client script to download the report


REQUIREMENT Rendering specific Groups in the assignment group
field based on reference qualifier

The assignment is rendered

Show only caller id groups in the assignement Assignment Group based on the output
Reference Field of the reference qualifier

group field
Short Description

Description
....

.......

24
Dictionary Override Assignment Group

Incident

Override Reference Qualifier

Reference Qualifier -
We begin to get the user groups in
Without writing any script include, write a single code to get the user groups and render for assignement group field, a java object which is converted
the javascript in the reference qualifier of that field. javascript: 'sys_idIN' + new global.ArrayUtil().convertArray(gs.getUser().getUserByID(current.caller_id).getMyGroups());
into an array, then to the syntax
sys_idIN, this will only list all
active groups of the user.
Notification
REQUIREMENT

Add automatically in notification subject line : HTML Message

Action Required! Create an On-Call Schedule ${mail_script:set_subject_13days}

for CWS by 13 days from current date


Get the current time with GlideDateTime

25
(function runMailScript(current, template, email,
email_action, event) {

Add 13 days with addDaysLocalTime method // Add your code here


Notification var nowTime = new GlideDateTime();
Email Script nowTime.addDaysLocalTime(13);
var subject = 'Action Required! Create an On-Call
Schedule for CWS Group by + nowTime.getDate();

create subject variable and store subject line + nowTime.getDate


email.setSubject(subject);

})(current, template, email, email_action, event);

To have a custom line in the email subject, create a email notification script, get the current time and add 13 days to it, then use this new Set the subject variable to the email setSubject in parameters
value in the subject line, the email notification script will be called from the notification html message body. this line will set the subject line
REQUIREMENT
Before Business Rule

ServiceNow

Check if any case task is in open state or


not, if it is abort action. Time A server side code can be executed after the
inbetween form submission and before the data gets
the form updated into the database.
submission Before Business Rule
and the This is called a Before Business Rule
databse
update For this requirement, write a Before
Business Rule on update for case table with
the following condition case state is
resolved
Database

26 (function executeRule(current, previous /*null when async*/) {


// Add your code here

var grCust = new GlideRecord("sn_customerservice_task");


grCust.addQuery("parent", current.getUniqueValue());
grCust.addEncodedQuery("state=1");
grCust.setLimit(1);
grCust.query();if (gr.next()) {
Before Business Rule

Create grCust object of GlideRecord Class table


sn_customerservice_task

Add query with the record sys_id and where state=1


gs.addErrorMessage("not allowed");
Refrain user to update any information on the case if the task is open, for that write a before Business Rule on current.setAbortAction(true);}})(current, previous);
update, the script will query the customerservice_task table, check if the state is open, if yes, it will abort the action.

if there is a record with these conditions Abort the


current action
REQUIREMENT

var JS_Watchlist_Manager = Class.create();


Script Include
manData method JS_Watchlist_Manager.prototype =
Object.extendsObject(AbstractAjaxProcessor, {

JS_Watchlist_Manager Script Include


Get the caller id with this manData: function() {

When the caller id changes, change the 2


getParameter
var subject_person =
this.getParameter('sysparm_subject_person');
manData method

watch list to the caller manager.


var grUser = new GlideRecord("sys_user");
grUser.addQuery("sys_id", subject_person);
grUser.query();
Create grUser object of
if (grUser.next())
GlideRecord Class - sys_user table {
return grUser.manager.toString();
JS_Watchlist_Manager SI }},

Query the table with the called id


type: 'JS_Watchlist_Manager'
});

if there is a record return caller


manager

27
function onChange(control, oldValue, newValue,
isLoading, isTemplate) {
1 Call the script include with GlideAjax
if (isLoading || newValue === '') {
return;
}
var ga = new
onchange client script GlideAjax('JS_Watchlist_Manager');
Add two parameters - 1 method name ga.addParam('sysparm_name', 'manData');
and the caller id, here the new value ga.addParam('sysparm_subject_person',
newValue);
ga.getXML(manParse);
onchange client
script on caller id get the xml response from manParse
function, call this function to send the }
field
Write a onchange client script for the caller field, the script will get the caller id and send this value as request and get the response
function manParse(response) {
input to script include, then the si will will the user id, run a query in the sys_user table to find out the var answer =
user manager return this value to client script, the client script will receive the manager info and update response.responseXML.documentElement.getAt
tribute("answer");
this value to the caller list field. ManParse Function
if(answer){
g_form.setValue("watch_list", answer);
parse the resonse and set the value to }
watch list }
Script Include getGroup method
var AssignedGroup = Class.create();
AssignedGroup.prototype =
AssignedGroup Create grUser object of GlideRecord class - Object.extendsObject(AbstractAjaxProcessor, {
sys_user_gmember table
REQUIREMENT getGroup: function() {
getGroup
var grUser = new GlideRecord('sys_user_grmember');
grUser.addQuery('group', this.getParameter('sysparm_ag'));
2 Get the group with this getParameter and grUser.query();
query var a = '';
while (grUser.next()) {
a += ',' + grUser.user.name;

When you select an assignement group, list


}
return a;
AssignedGroup SI },
Define an empty a variable

all users of this group in another custom list


type: 'AssignedGroup'
});

field
for each record the system is processing with
the while loop, store the user name in the a
variable

Return a

28 1 Call the script include with GlideAjax


function onChange(control, oldValue, newValue,
isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
Write a onchange client script for the assignement group field, the script will get the assignment group var ga= new GlideAjax('AssignedGroup');
onchange client script Add two parameters - 1 method name and 2 ga.addParam('sysparm_name','getGroup');
and send this value as input to script include, then the si will will the group, run a query in the ga.addParam('sysparm_ag',g_form.getValue('assignme
the assignment group new value
sys_gmember table to find out all users of that particular group return this value to the client script, the nt_group'));
ga.getXML(getDetails);
client script will receive all users info and update this value to the custom assigned group list field. onchange client
script on get the xml response from getDetails function getDetails(response){
assignment group function, call this function to send the
field request and get the response var
answer=response.responseXML.documentElement.get
Attribute("answer");
alert("The Members are:"+ answer);
getDetails Function g_form.setValue('u_assigned_group_list',answer);
}
}
parse the response and set the value
to assigned group list
REQUIREMENT

Populate data from incident form to outage define url


createOutageM2M();

form with an ui action. function createOutageM2M() {

var url = "cmdb_ci_outage.do?sys_id=-1&sysparm_query=";


encode uri with cmdb_ci, short description url += encodeURIComponent("cmdb_ci=" + current.getValue("cmdb_ci")
UI Action and task number to send as input + "^task_number=" + current.getUniqueValue() + "^short_description="
Script + current.getValue("short_description") + "^EQ");

action.setRedirectURL(url);
action.setReturnURL(current);}

29
redirect url and return url

the ui action will call a script, which will have encoded url, the url is created with field names and values, see example in the
next page, redirect and return url to update information in outage form
REQUIREMENT Display Business Rule

Database Server
System is During the lapse of time when the

When a user create an incident autopopulate the loading


and
system renders first the form and
before the access is given to the user
rendering in order to work with the form, a
user as assigned to and aslo mention his first group the form server side script can be executed,
this is a called a Display Business

in assignement group Display Business Rule Rule.

onLoad Client Script

Yellow
ServiceNow

30 When user or
system changes
a field value onload Client script
Client
During the lapse of time when the system
renders first the form and before the
access is given to the user in order to
work with the form, onLoad Client Script
is executed

To populate the group, create display business rule, ge the loggedin user groups and assign the first group to the assignement group field, Such client script allows us to configure
to populate assigned to value on record creation, create a onload client script, check the current record is new record, then get the logged forms, forms field and field values
Yellow
in user id and set the value to assigned to field. ServiceNow
Display Business Rule

Server
Database

System is During the lapse of time when the


loading system renders first the form and
and before the access is given to the user
(function executeRule(current, previous /*null when async*/) {
// Add your code here rendering in order to work with the form, a
Create a Display Business Rule for the incident table,
1 get the user groups, convert into an array and
the form server side script can be executed,
var groups = new this is a called a Display Business
global.ArrayUtil().convertArray(gs.getUser().getMyGroups()); assign the user first group to assignment group Rule.
Display Business Rule
if(groups.length > 0){

current.assignment_group = groups[0];

}})(current, previous);

onLoad Client Script

Yellow
ServiceNow

When user
Client
or system
changes a During the lapse of time when the system
field value onload Client script renders first the form and before the
function onLoad(){ access is given to the user in order to
work with the form, onLoad Client Script
if(g_form.isNewRecord()){
is executed
2 Create a onLoad Client script on the incident table
g_form.setValue('assigned_to', g_user.userID); get the user id and assign the value to assign_to
field Such client script allows us to configure
} forms, forms field and field values
Yellow
ServiceNow
}
REQUIREMENT

onLoad Client Script

Get specific value from a string Servicenow Form

onload script

During the lapse of time


when the system renders
Define an URL
first the form and before var url = 'https://devxxxxx.service-now.com/sp?
the access is given to the id=sc_cat_item&sys_id=d121a42c1b5ab4903188fc8e034bc

31
user in order to work with be3&operation=modify&company=7de31002db3be0104d4
the form, 767e81396194c&record_sys_id=78726b201bcffc908afeca6
5624bcb7c';
onLoad Client Script is
executed Such client script Get the record sys_id with URLSearch Params var value = new URLSearchParams(url).get('record_sys_id');
allows us to configure
forms, forms field and field alert(value);
values

Good To Know :
onLoad Client Script

User URLSearchParams class to get specific values from a string, try this code on onload client script.

Servicenow rendered Form


REQUIREMENT onchange Client Script

Servicenow Form submission start

Check for a custom date field, if is


smaller than 31st Dec 2099, if not clear
the field value onload script

get the end date from new value variable


and store it in end date varibale
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '')
{return;}
var endDate = new Date(getDateFromFormat(newValue, g_user_date_format));
var finalDate = new Date(getDateFromFormat('2099-12-31', g_user_date_format));

32
This script runs when a
particular value define a final date variable and the if(endDate.getTime() > finalDate.getTime()){
value 2099-12-31
alert('Please give end date before 31st Dec 2099');

g_form.clearValue('u_end_date');}}

if the end date is superior than final date, alert


error message, clear values from the end date

Write onchange client script for end date custom date field for the incident table, define end date variable and
get the value from newValue, define final date variable , set a 2099-12-31 as value in the parameter, compare
end date to final date, if it is bigger, alert error message and clear value for the end date field

Servicenow form submitted


REQUIREMENT
Before Business Rule

ServiceNow

End date on incident form should not be


smaller than the Start date. Time
inbetween A server side code can be executed after the form
the form submission and before the data gets updated into the
submission Before Business Rule database.
and the
This is called a Before Business Rule
database
update

Database

33 (function executeRule(current, previous /*null when async*/)


{/

var start = new GlideDateTime(current.start_date).getNumericValue();

var end = new GlideDateTime(current.start_date).getNumericValue();

if(start > end){


Before Business Rule
Get the start time and time with GlideDateTime Object and
getNumericValue method will return the int value of specificed
character and store in start and end variables

if the start date time is superior than end date time

gs.addErrorMessage("Please give valid start and end dates");

current.setAbortAction(true);
}})(current, previous);

For this requirement, write a rule before database update, on record creation and updates, if the start date is superior than Abort the current action
end date, it will abort the action
REQUIREMENT

Substract 3 days to a date field in the Script and Diagrams for this requirement

incident form with a script Create grInc object of GlideRecord Class table incident

var grInc = new GlideRecord('incident');


grInc.addQuery('number', 'INC5528036');
grInc.query(); Add query with the incident number and query
while(grInc.next())
{

34
var date = new GlideDateTime(grInc.u_closed_date);
date.addDaysUTC(-3);
grInc.setValue('u_updated_date',date.getValue());
grInc.update(); for each record processed by the systeme during the while
loop, store in the date variable the u_closed_date time,
} substract 3 days, then set this value to u_updated field
and update

Write a server script which will get values from a custom date field (u_closed_date) and substract three days, then
set this value to another custom date field, updated date field, test this script in the background script for a specific
incident.
REQUIREMENT onchange Client Script

Servicenow Form submission start

In a list type referencing kb records,


limit the selection up to 3 records
onchange script

get the kb list length and store the value in the


length variable.
begin by getting the field values, make to string
This script runs when a function onChange(control, oldValue, newValue, isLoading) {
then split if (isLoading || newValue == '')
particular value changes
{return;}

var length = g_form.getValue('u_kb_list').toString().split(',').length;

35
if length is more than 3. get all values of kb_list if( length>3){
field in a list array, you can then splice the list
var list = g_form.getValue('u_kb_list').toString().split(',');
array and delete the fourth element if it is list.splice(3,1);
selected by the user. g_form.setValue('u_kb_list',list);
set the values for kb_list field with the values
alert("not allowed");}
available in the list array.
}

Servicenow form submitted


Create a onchange client script for the list type field, and get the kb value, make it as string then split it, check if the
length is more than 3, if yes alert not allowed. see the script in the next page.
REQUIREMENT

Script and Diagrams for this requirement


Delete record which are work in progress
Create grInc object of GlideRecord Class table incident

var grInc = new GlideRecord('incident');


grInc.orderByDesc("sys_created_on");
Order Inc by Order Date
grInc.addActiveQuery();

36
grInc.addEncodedQuery('state=2');

grInc.query();
Query active record with the state in Progress
grInc.next();
while(grInc.next()){

grInc.deleteRecord();}

for each record that the system process in a while loop,


delete the record

Write a background script, begin first to query all active records with the state in progress and then
delete it.
REQUIREMENT

Get the number of tickets assigned to each


Creating count Object of the class GlideAggregate for incident

assignment group in incident table with a var count = new GlideAggregate('incident');


table, GlideAggregate is an extension of GlideRecord. It provides the
capability to do aggregation (COUNT, SUM, MIN, MAX, AVG).

script count.groupBy('assignment_group');

count.addAggregate("COUNT");
Group By assignment group and with groupBy method and count,
count.query();
and then query, this is giving a filtered list of incidents by
while (count.next()) { assignment group and their count. ex hardware 13

37
var category = count.assignment_group.getDisplayValue();

var cnt = count.getAggregate("COUNT");


For each group records processed by the system in while loop, assign
gs.info("NO. of incidents assigned to "+category+ " is "+cnt);
the assign group value to category variable and count number to cnt.
} print category and cnt.

Write a script which will filter all incidents by group and count the number record for each group.
REQUIREMENT

onLoad Client Script

Disable Attachement icon in Servicenow Form

incident form

onload script

During the lapse of time


when the system renders
Disable attachments function onLoad(){
first the form and before
the access is given to the
g_form.disableAttachments(); // hides the paper-clip icon}

38
user in order to work with
the form,

onLoad Client Script is


executed Such client script
allows us to configure
forms, forms field and field
values

Servicenow rendered Form

Hide paper clip icon with a onload client script for the incident table
REQUIREMENT

Groups User View User

If a logged in user is member of any of those 5 CAB Approval CAB Approval Other Groups

groups then show all groups including those 5.


Database Database
If a logged in user is not member of any of those
5 groups then show all groups excluding those 5 Hardware Hardware

groups. Helpdesk Helpdesk

Network Network

39
Other Groups Other Groups

Example of expected result, a user part of helpdesk, one of the five groups, he/she can see all groups including
those five, on the contrary a user who is not part of the five groups can only see all other groups and not those 5
groups.
Rendering specific Groups in the assignment group
field based on reference qualifier

The assignment is rendered


Assignment Group based on the output
Reference Field of the reference qualifier
var GlideGroup = Class.create();
Script Include GlideGroup.prototype = { GlideGroup Script Include
Short Description initialize: function() {
GildeGroup Script Include },

checkGroup: function(){
Description
.... checkGroup(); Method

var groups ='CAB Approval,Database,Hardware,Help Desk,Network';


.......
var grmember = new GlideRecord("sys_user_grmember"); Create groups Variable and store groups
grmember .addQuery("group.name", "IN" ,groups);
grmember .addQuery("user", gs.getUserID());
grmember .setLimit(1);
grmember .query();
if(grmember .next()){
Create grmember object of GlideRecord Class table
sys_user_grmember
Dictionary Override Assignment Group query ="";
}
else{
query ="nameNOT IN" + groups;
Incident }
return query;
},},
type: 'GlideGroup' grmember.query : querying the table by login user and groups
};
checkGroup function
Override Reference Qualifier

for each record processed by the system during the while loop, set
empty values for the query variable , else set nameNOTIN"+groups,
Reference Qualifier - for the query variable, return the query variable.

When query is empty, it will all groups including those 5 groups, when
javascript: new GlideGroup().checkroups();
the query is returned with nameNOTIN+ groups, it will exclued those 5
groups from list.
confirgure the dictionayr field, check the Override Reference
Qualifier and call the Script include from RQ

Override the reference qualifier for the assignment group field, the reference qualifier will call a script include and its method,
the script will run a query on the user group member table to filter members part of those 5 groups, if there is a user , the code
will return an empty value, therefore the assignement group will list all the groups, if the loggedin user is not part of this group, it
will return NameNOTIN + groups, which will list all groups and exclude those 5 groups.
REQUIREMENT

Send email notification for Case is not


sendEmail();
Calling giveRole function

1
function sendEmail(){

closed and reached 90 days


try{

Notification gs.info("Job run started::" + new GlideDateTime());


2 usergr is a GlideRecord Object of Sys_user Table

var gr = new GlideRecord('sn_hr_core_case');

gr.addActiveQuery();

gr.query();while (gr.next()) {
Notifcation is sent when
var gdStart = new GlideDateTime(gr.sys_created_on);
3 usergr.query();

reached90.days event is fired


var nowTime = new GlideDateTime(); user a user b user c
var date_diff = GlideDateTime.subtract(gdStart, nowTime);

var nDays = parseInt(date_diff.getNumericValue()/86400000);//


if diff is 90 daysif (nDays == 90) {
4
gs.eventQueue('event_name', gr, gr.assigned_to);

}}
giveRole function
5urolegr is a GlideRecord
Object of sys_user_has_role urolegr is a GlideRecord urolegr is a GlideRecord
gs.info("Job run completed::" + new GlideDateTime()); Table Object ... Object ...

40
}

catch(ex){

gs.info('Exception'+ex);
6
Adding Query

Event Registry
}}

reached90.days 7
!urolegr .next()==true

urolegr .next()==true
sendEmail();
Calling giveRole
function

function sendEmail(){

try{

Create grInc object of GlideRecord Class table


Notification gs.info("Job run started::" + new GlideDateTime());
sn_hr_core_case
var grcase = new GlideRecord('sn_hr_core_case');

grcase.addActiveQuery();

grcase.query();
Notifcation is sent when while (grcase.next()) { run query to get all active cases
var gdStart = new GlideDateTime(grcase.sys_created_on); giveRole function
reached.days event is fired
var nowTime = new GlideDateTime();
for each record the system process in a while loop, get
var date_diff = GlideDateTime.subtract(gdStart, nowTime);
create time store in start variable, get the current time
var nDays = parseInt(date_diff.getNumericValue()/86400000); and store it nowTime variable,
calculate the difference in numerical value divide by
// if diff is 90 days 86400000 to get the number of days
if (nDays == 90) {

gs.eventQueue('event_name', grcase, grcase.assigned_to);

}} if days is more than 90 , queue reached.days event, the


event is already regitered in the event regsitry
gs.info("Job run completed::" + new GlideDateTime());

catch(ex){
Event Registry
gs.info('Exception'+ex);

reached.days
}}
REQUIREMENT var rec = new GlideRecord('incident'); //replace
rec New GlideRecord(incident);
with actual name of table 1
Instance of GlideRecord New Keyword to create the instance

Creating a on Object of from the class GlideRecord for Incident table

Remove Incident Records created before a


rec.addEncodedQuery('sys_created_on<javascript
:gs.dateGenerate('2021-11-03','00:00:00')');
2 AddEncodedQuery(.... );
rec
<
specific date
sys_created on gs dateGenerate(...)

Using rec object and AddEncodeQuery , add query to get records created before 2021-11-03
AddEncodedQuery('sys_created_on<javascript:gs.dateGenerate('2021-11-03','00:00:00')');
gs is an object of GlideSystem and its method dateGenerate turn the input into date so it is
comparable to the sys_created_on field value

rec.query();

3
rec query();

41
now run a query for the result

4
while (rec.next())
{ result

rec next(); rec next(); ... ..

0 1 ..
user rec object with next () method to load the next record for processing, this
Test the script in background to see the result. while is done for each existing record retuned by the query

5
rec.deleteRecord();

} rec deleteRecord(); rec deleteRecord(); ... ....

each the code process the record , it deletes it


REQUIREMENT

role New
1 GlideRecord(sys_group_has_role);

Instance of GlideRecord New Keyword to create the instance


var role = new GlideRecord('sys_group_has_role');
Creating a on Object of from the class GlideRecord for sys_group_has_role table

Script to add role to group


role.initialize(); 2 role initialize();

Before an insert, use initialize, part of best practices

role.group = '<sys_id of group>';


3 role.group sys_id of group

42
Use role object to dot walk group field, sys_id of the group is the value that is assign

role.role = '<sys_id of admin role>';


4 role.role sys_id of admin role

Use role object to dot walk role field, sys_id of admin role is the value that is assign

role.inherits = true;
Test the script in background and check the appropriate group 5 role.inherits true

A user who gets this role will also be part of this group

role.insert();

6
role insert();

insert a record in the table


REQUIREMENT
1 str '[{"label":"value1"},{"label":"value2"},{"label":"value3"}]'
var str = '[{"label":"value1"},
{"label":"value2"},{"label":"value3"}]';
Define str variable and store a json string representation

[{"lable":"value1"},{"label":"value2"},{"label":"value3"},{"label":"value4"},{"label":"value5"}..
2 parser JSON parse(str)

From the text above, extract on


var parser = JSON.parse(str);

Turn the string into javascript object with parse method and store the result into the parser variable

values and push into an Array. var arr = []; 3 arr []


Define an empty array

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

For loop

i= 0 i= 1 i= .. i= 3 i smaller than parser length

var val = parser[i].label;


4 val parser[i] label

Test the script in background to see the result

arr.push(val.toString()); 5
}
arr push( val toString() );

Pushing val values into the array variable for each iteration in the for loop
gs.info('my values->' + arr.toString());
REQUIREMENT

Check if the current user is part of group listed in a


system property, if it is true, the channel field should
have the following group as value ''Help Desk" During the lapse of time when the system renders
first the form and before the access is given to the
Database
user in order to work with the form, a server side
script can be executed, this is a called a Display
Business Rule.

System is
loading g_scratchpad
and Display Business Rule
rendering

44
the form
A Display Business Rule can instantiate g_scratchpad
object which can be passed to the client side and it
can be used in client script.

ServiceNow
rendered form

In order to change the value in the channel field based on the current logged in user, make use of a script include to check the user
group and a Display Business Rule to update specific value in the channel field.
Database

var GlideUser = Class.create();


Script Include GlideUser.prototype = { GlideUser Script Include
System is Display Business Rule initialize: function() {
loading GildeUser Script Include },
and
rendering 2 If Condition is True checkGroup(); Method
the form 1
checkGroup: function(){ With getProperty method of GlideSystem class, get the propety
value of IT.Helpdesk, this property contains the groups
3 current.channel.setDisplayValue("Help Desk");
var groups = gs.getProperty('IT.Helpdesk');

Create grmember object of GlideRecord Class -


var grmember= new GlideRecord("sys_user_grmember"); sys_user_gmember Table
grmember.addQuery("group.name", "IN" ,groups);
grmember.addQuery("user", gs.getUserID());
grmember.setLimit(1);
checkGroup function
grmember.query();
ServiceNow rendered form grmember.query : querying the table by loggined user and groups,
groups variable contains specified groups
return grmember.hasNext();
},

type: 'GlideUser' After the query, return grmember.hasNext(); it this statement is true
}; there is a record with the above condition /filter - false, there is no
such record.

Display Business Rule and Script Include True return, will execute the Business rule

Display Business Rule has two things, the first one is the script which update the channel to Helpdesk, the second one, it is
the condition field which contains the script include and the method. the script will check if the current user is part of group
listed in the system property, if yes the condition will then be true, which allows the br to update the field. prior to create the
br, define the system property with some groups in it.
REQUIREMENT

Make a ui action button make visible to just name ui_test application global

the members from the assignment group table incident

active

condition gs.getUser().isMemberOf(current.assignment_group);

45
Use a script in the condition field of the ui action, to check the members group and make it visible according to the
result
REQUIREMENT

onLoad Client Script

When a user is creating a new incident Servicenow Form


record, if he doesn't have the
incident_impact_urgency_write role remove
onload script
high and medium impact options check if the current user has impact urgency role with
1 hasRoleExactly method ( part of g_user class) store the result in
During the lapse of time
the user, the result is either true or false

46
when the system renders function onLoad() {
first the form and before
var user = g_user.hasRoleExactly('incident_impact_urgency_write');
the access is given to the
user in order to work with
the form,
2 With isNewRecord method (part of g_form
if (g_form.isNewRecord()) {
class) check if the form is loading

onLoad Client Script is


executed Such client script
allows us to configure
if (user == false){
forms, forms field and field if the user value is false, which means, the user doesnt have the role.
values 3 Remove high and medium options with removeOptions method(part of g_form.removeOption('impact', '1');
g_form.removeOption('impact', '2');
g_form class)
mention the impact database name and its value for remove option }
}
}

Simple client to get the caller id and alert it, this is onload client script

Servicenow rendered Form


REQUIREMENT

1
Take all values from a certain field on
create an empty array

all active records and add them to an var subjectsArray = [];

var auto = new GlideRecord('u_alert_auto_close');


2 create auto object with GlideRecord Class - table
u_alert_auto_close

array auto.addQuery('u_active', true);


With the method addQuery(); look for active record
auto.query();
3 and query

47
while(auto.next()){

var subjects = auto.getValue('u_closed_alert_subject');


4
subjectsArray.push(subjects);

}
While loop, each time the record is processed
from the table u_alert_auto_close
gs.print(subjectsArray);
get the value with getValue method(part GlideRecord
Class)
and with the auto object, store the value in the subject
variable

before processing the next record, push the subject


value into an subjects Array.

subjects variable value will change each time the


Write a a background script which query the table and collect values record is processed, subjectArray will keep storing all
values by indexing them. It's an array
REQUIREMENT

Retrieve particular data from below JSON


{"schemaId":"AzureMonitorMetricAlert","data":{"version":"2.0","properties":null,"status":"Deactivated","context":{"timestamp":"2021-10- 1 create a Variable const which stores the JSON string
12T09:53:09.8443362Z","id":"/subscriptions/933c2f10-9eff-49d0-a490-60ce1c3a0c72/resourceGroups/EU-HUB-PRD-AUT- const json = '{"schemaId":"AzureMonitorMetricAlert","data":
{"version":"2.0","properties":null,"status":"Deactivated","context":{"timestamp":"2021-10-
RG001/providers/microsoft.insights/metricalerts/EU-MON-LINUX-DISK-CRITICAL-Alert01","name":"EU-MON-LINUX-DISK-CRITICAL- 12T09:53:09.8443362Z","id":"/subscriptions/933c2f10-9eff-49d0-a490-60ce1c3a0c72/resourceGroups/EU-
Alert01","description":"The Alert is triggered because one of the linux server instance used space is more than HUB-PRD-AUT-RG001/providers/microsoft.insights/metricalerts/EU-MON-LINUX-DISK-CRITICAL-
Alert01","name":"EU-MON-LINUX-DISK-CRITICAL-Alert01","description":"The Alert is triggered because one of
95%.","conditionType":"SingleResourceMultipleMetricCriteria","severity":"3","condition":{"windowSize":"PT15M","allOf":[{"metricName":"Average_% Used the linux server instance used space is more than
Space","metricNamespace":"Microsoft.OperationalInsights/workspaces","operator":"GreaterThan","threshold":"95","timeAggregation":"Average","dimensio 95%.","conditionType":"SingleResourceMultipleMetricCriteria","severity":"3","condition":
{"windowSize":"PT15M","allOf":[{"metricName":"Average_% Used
ns":[{"name":"Computer","value":"EU-HUB-MON"}, Space","metricNamespace":"Microsoft.OperationalInsights/workspaces","operator":"GreaterThan","threshold":"9
5","timeAggregation":"Average","dimensions":[{"name":"Computer","value":"EU-HUB-MON"},
{"name":"InstanceName","value":"/"}],"metricValue":91,"webTestName":null}]},"subscriptionId":"933c2f10-9eff-49d0-a490-
60ce1c3a0c72","resourceGroupName":"eu-hub-prd-aut-rg001","resourceName":"EU-HUB-MON-LAWS-
{"name":"InstanceName","value":"/"}],"metricValue":91,"webTestName":null}]},"subscriptionId":"933c2f10-9eff-
49d0-a490-60ce1c3a0c72","resourceGroupName":"eu-hub-prd-aut-rg001","resourceName":"EU-HUB-MON- 2 Use the JSON parse method to parse it the string and
01","resourceType":"Microsoft.OperationalInsights/workspaces","resourceId":"/subscriptions/933c2f10-9eff-49d0-a490-
LAWS-01","resourceType":"Microsoft.OperationalInsights/workspaces","resourceId":"/subscriptions/933c2f10-
9eff-49d0-a490-60ce1c3a0c72/resourceGroups/eu-hub-prd-aut-
store it in the obj variable
rg001/providers/Microsoft.OperationalInsights/workspaces/EU-HUB-MON-LAWS-
60ce1c3a0c72/resourceGroups/eu-hub-prd-aut-rg001/providers/Microsoft.OperationalInsights/workspaces/EU-HUB-MON-LAWS- 01","portalLink":"https://portal.azure.com/#resource/subscriptions/933c2f10-9eff-49d0-a490-
01","portalLink":"https://portal.azure.com/#resource/subscriptions/933c2f10-9eff-49d0-a490-60ce1c3a0c72/resourceGroups/eu-hub-prd-aut- 60ce1c3a0c72/resourceGroups/eu-hub-prd-aut-
rg001/providers/Microsoft.OperationalInsights/workspaces/EU-HUB-MON-LAWS-01"}}}';
rg001/providers/Microsoft.OperationalInsights/workspaces/EU-HUB-MON-LAWS-01"}}}

const obj = JSON.parse(json);


alert(obj.data.version);
3 After scrutinizing the JSON, alert the value you
alert(obj.data.context.condition.allOf[0].dimensions[0].value); want, example : alert(obj.data.version);
alert(obj.data.context.condition.allOf[0].dimensions[1].name);

48
Write a script to parse json string
REQUIREMENT

Add a string field, in the calculated tab, check calculated


Add an additional field on a table use the script below.

which will add values of two current refers to record object, retrieve description values like this current.description, same
logics for other fields.

different fields from the same table. store the concatenate value in a new field, and return it.

Example short description and var values = current.description + ' ' + current.short_description;
return values; // return the calculated value
description in one field
table incident application global

type string active

49
column label Add Two Field Values

calculated value

calculated

(function calculatedFieldValue(current) {

var values = current.description + ' ' +


current.short_description;
return values; // return the calculated value

})(current);
REQUIREMENT

Concatenate the values of the 2 fields Add a string field, make it as function field
use the following code :

and display them in 1 field. glidefunction:concat(description, , ,short_description)

table incident application global

type string active

column label Add Two Field Values Function Field function field

50
function
glidefunction:concat(description, , ,short_description)

You might also like