0% found this document useful (0 votes)
73 views48 pages

JavaScript Basics: Alerts, Loops, and Strings

The document provides an overview of JavaScript basics, including alerts, console logging, string methods, loops, conditionals, arrays, objects, and functions. It also covers ServiceNow client-side scripting, detailing UI policies, client scripts, and Glide Form methods. Key examples illustrate how to manipulate strings, handle user input, and implement logic in scripts.

Uploaded by

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

JavaScript Basics: Alerts, Loops, and Strings

The document provides an overview of JavaScript basics, including alerts, console logging, string methods, loops, conditionals, arrays, objects, and functions. It also covers ServiceNow client-side scripting, detailing UI policies, client scripts, and Glide Form methods. Key examples illustrate how to manipulate strings, handle user input, and implement logic in scripts.

Uploaded by

m.gradzewicz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Alert(„test”); - creates a pop-up with text in brackets

[Link](“text”); - writes text in brackets in console

Confirm(“do you want to continue?”); - creates a pop-up with text in bracket and two options “OK”
“Cancel”

Prompt(“Enter some text”); - creates a pop-up asking user to enter some text; asks for user input

Alert(1); - prints “1” in a pop-up window

Alert(1+2); - prints “3”

Alert(“Total number of apples is ” + (2+2)); - prints text and add operation

Var x=7; - declare a variable;


var firstname=’Mike’;
var lastname=’Tyson’;
alert(first name + “ “ + lastname);

var firstname = prompt("Enter first name");


var lastname = prompt("Enter last name");
alert(firstname + " " +lastname);

USEFUL STRING METHODS


Length
The length property returns the length of a string.

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

var sln = [Link];

IndexOf
The indexOf() method returns the index of (the position of) the first occurrence of a
specified text in a string

var str = "Please locate where 'locate' occurs!";

var pos = [Link]("locate");

The lastIndexOf() method returns the index of the last occurrence of a specified text
in a string:

var str = "Please locate where 'locate' occurs!";

var pos = [Link]("locate");

Both indexOf(), and lastIndexOf() return -1 if the text is not found.


var str = "Please locate where 'locate' occurs!";

var pos = [Link]("John");

Search
The search() method searches a string for a specified value and returns the position
of the match:

var str = "Please locate where 'locate' occurs!";

var pos = [Link]("locate");

SLICE
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not
included).

var tabela = "123456789";


[Link]([Link](3,5))

*** Script: 45

- Slices string after first value till after second value


- Second value can be negative so it counts from the back

SUBSTRING

var tabela = "123456789";


[Link]([Link](3,5))

*** Script: 45

- Similar to slice but doesn’t work with negative values

SUBSTR

var tabela = "123456789";


[Link]([Link](3,5))

*** Script: 45678

- Second parameter defines the length here, not position till


REPLACE(“existing word”, “new word”)

var x = "I am flying coach";


var y = [Link]("I am", "We are")

[Link](y)

var x = "I am learning ServiceNow";


var y = [Link](/SERVICENOW/i, "scripting")

[Link](y)
*** Script: I am learning scripting

var x = "I am learning ServiceNow";


var y = [Link](/SERVICENOW/, "scripting")

[Link](y)
*** Script: I am learning ServiceNow
/i – makes it case insensitive

var x = "I am learning ServiceNow ServiceNow";


var y = [Link](/ServiceNow/g, "scripting")

[Link](y)
*** Script: I am learning scripting scripting
/g – makes it a global match and replaces all

var x = "I am learning serviceNow ServiceNow";


var y = [Link](/ServiceNow/gi, "scripting")

[Link](y)
*** Script: I am learning scripting scripting
/gi – you can combine both global match and case insensitive

TOUPPERCASE() – transform string into all upper case

TOLOWERCASE() – transform string to all lower case

TRIM() – remove spaces from both sides of a string

CONCAT() - concat() joins two or more strings:

var text1 = "Hello";

var text2 = "World";


var text3 = [Link](" ", text2);

CharAt
The charAt() method returns the character at a specified index (position) in a string:

var str = "HELLO WORLD";

[Link](0);// returns H

CharCodeAt
The charCodeAt() method returns the unicode of the character at a specified index in
a string:
The method returns a UTF-16 code (an integer between 0 and 65535).

var str = "HELLO WORLD";

[Link](0); // returns 72

Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:

var str = "HELLO WORLD";

str[0]; // returns H

Converting a String to an Array


A string can be converted to an array with the split() method:

var txt = "a,b,c,d,e"; // String

[Link](","); // Split on commas

[Link](" "); // Split on spaces

[Link]("|"); // Split on pipe

var txt = "Hello"; // String

[Link](""); // Split in characters

INCLUDES() – returns true/false if destination string contains value

FOR LOOP

for(var i = 1; i<=10; i++) //3 arguments in brackets


{
[Link](“2 x “ + I +” = ” +(2*i));
}

var x = prompt("enter number");


for(i=1;i<=20;i++)
{
[Link](x + "x" + i + "=" + (x*i));
}

WHILE LOOP

var x=prompt("Enter number");


var i=10;
while(i<20) //1 argument in brackets
{
[Link](x + " x " + i +" = " + (x*i));
i++;
}

IF … ELSE …

X%2 - % zwraca reszte z dzielenia

var x = 6;
if (x%2 == 0)
{
[Link](x + " is even.");
}
else
{
[Link](x + " is odd.");
}

var x = prompt("Enter a number.");


if (x%2 == 0)
{
[Link](x + " is even.");
}
else
{
[Link](x + " is odd.");
}
IF … ELSE IF …

var x = prompt("Please enter a number 1-7");


if (x==1)
[Link](x + " is Monday");
else if (x==2)
[Link](x + " is Tuesday");
else if (x==3)
[Link](x + " is Wednesday");
else if (x==4)
[Link](x + " is Thursday");
else if (x==5)
[Link](x + " is Friday");
else if (x==6)
[Link](x + " is Saturday");
else if (x==7)
[Link](x + " is Sunday");
else
[Link]("Input should be between 1 and 7");
SWITCH

var x = prompt("Please enter a number 1-7");


switch(x)
{
case "1" : [Link](x + " is Monday");
break; // if case is satisfied it doesn’t go through other cases
case "2" : [Link](x + " is Tue");
break;
case "3" : [Link](x + " is Wed");
break;
case "4" : [Link](x + " is Thu");
break;
case "5" : [Link](x + " is Fri");
break;
case "6" : [Link](x + " is Sat");
break;
case "7" : [Link](x + " is Sun");
break;
default: //if the cases are not satisfied it gives back this
[Link]("Wrong number")

NESTED LOOPS

var x = prompt("Enter number");


for(i=1; i<=x; i++)
{
if (i%2==0)
{
[Link](i + " is even");
}
else
{
[Link](i + " is odd");
}

ARRAYS

var cars = ["Audi","BMW","Mercedes"];

[Link](cars[1]);

var cars = ["Audi","BMW","Mercedes"];

[Link]([Link]); // .length – gives back table size


var cars = ["Audi","BMW","Mercedes"];

for(i=0; i<[Link]; i++)


{
[Link](cars[i]);
}

OBJECTS

var car = {}; // declaring object


[Link] = "Mercedes";
[Link] = "White";
[Link] = "Electric";

[Link]("Car type is " + [Link]);

…………………………………………………………………………………………………………………………………………….

var car1 = { name : "Mercedes", color: "white", type: "electric" };


var car2 = { name : "BWM", color: "black", type: "diesel" };
var car3 = { name : "Audi", color: "red", type: "petrol" };

[Link]([Link]);

…………………………………………………………………………………………………………………………………………….

var cars = [
{ name : "Mercedes", color: "white", type: "electric" },
{ name : "BWM", color: "black", type: "diesel" },
{ name : "Audi", color: "red", type: "petrol" }
];
[Link](cars[0]);

…………………………………………………………………………………………………………………………………………….

var cars = [
{ name : "Mercedes", color: "white", type: "electric" },
{ name : "BWM", color: "black", type: "diesel" },
{ name : "Audi", color: "red", type: "petrol" }
];

for (i=0; i<[Link]; i++)


{
[Link]("My car " + (i+1) +" is " + cars[i].name + " ,color is " + cars[i].color + " ,type is " +
cars[i].type );
}

FUNCTIONS

var x = 2;
var y = 5;

[Link](x + " + " + y + " = " + (x+y));


……………………………………………………………………………………………………..

var x = 2;
var y = 5;
var z = (x+y)*2/100;

var a = 10;
var b = 20;
var c = (a+b)*2/100;

[Link]("(" + x + " + " + y + ")*2/100 = " + z); //these two are the same just diff vari
[Link]("(" + a + " + " + b + ")*2/100 = " + c); //ables; better to write a function
……………………………………………………………………………………………………..

var x = 2;
var y = 5;

calculation(x,y); // calling the function

var a = 10;
var b = 20;

calculation(a,b); // calling the function

function calculation(x,y) //function definition


{
var z = (x+y)*2/100;
[Link]("(" + x + " + " + y + ")*2/100 = " + z);
}
……………………………………………………………………………………………………..

var x = 2;
var y = 5;

[Link](calculation(x,y)); //prints the z value

var a = 10;
var b = 20;

[Link](calculation(a,b));

function calculation(x,y)
{
var z = (x+y)*2/100;
return z; //returns value so it can be called
} //outside of function
var x = 2;
var y = 5;

var z= calculation(x,y); //store output of function in a variable


[Link](z*1.3); //print output * 1.3

var a = 10;
var b = 20;

var c = calculation(a,b);
[Link](c*1.2);

function calculation(x,y)
{
var z = (x+y)*2/100;
return z;
}

var test = "My first name is Mike My last name is Tyson";


[Link](test);

var test = "My first name is Mike \nMy last name is Tyson"; // \n moves to next line
[Link](test);
SERVICENOW

1. UI Policy – Client side


Use when you want to make a field Mandatory or Read Only or for Visibility based on conditions.
You can’t set a value to a field with UI Policies. Can set field attributes without scripting. Cannot be
executed on form save/submit/update.

2. Client Script – Client side


Client script executes before UI policy.

There are 4 types of client scripts:


 OnChange - form level only
 OnSubmit - form level only
 OnLoad - form level only; used to repopulate the form
 OnCellEdit - list level only

To access the form you use “g_form”


What is Glide Form and usage (g_form):
The Glide Form is client-side API, mainly used to change default behavior of the current record.
Glide Form methods are only running on the client side (Browser).
The global object g_form is used to access Glide Form methods.
These methods are used to make custom changes to the form view of records. All validation of
examples was done using Client Scripts.
g_form methods frequently using in Client Scripts.
g_form methods can use in catalog client script too.

Glide Form Methods

setValue() getFormElement()
getValue() getSection()
addOption() getTableName()
removeOption() getUniqueValue()
addInfoMessage() hideRelatedLists()
addErrorMessage() isMandatory()
clearMessage() save()
clearOptions() submit()
disableAttachments() setDisabled()
enableAttachments() setDisplay()
Flash() setMandatory()
getActionName() setVisible()
getControl() setReadOnly()
getElement() setSectonDisplay()
showErrorBox() showRelatedList()
showFieldMsg() showRelatedLists()
addDecoration() isNewRecord()
removeOption() hideFieldMsg()

g_form.setValue(“field name”, “what value you want to set”, )

 OnLoad

function onLoad() {
g_form.setValue("short_description", "testing if this works")
}

 OnChange

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


if (isLoading || newValue === '') {
return;
}
var sd = g_form.getValue("short_description");
if (sd == "welcome" || sd == "Welcome") {
g_form.setValue("description", "lets see if this works");
g_form.setReadOnly("description", true);
} else {
g_form.clearValue("description");
g_form.setReadOnly("description", false);
}
}

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


if (isLoading || newValue === '') {
return;
}
var sc = g_form.getReference("assigned_to", getDetails);

function getDetails(sc){
var email = [Link]
g_form.setValue("description", email);
}

//When using the .getReferrence its best to use a callback function (here getDetails) so that the
browser doesn’t get stuck. First we ask SNOW for all information from the reference table via
“assigned to”. Then once we get a response via callback, the function will be performed.

CTRL + SHIFT + J – opens the console and JS executor in SNOW

Client script to prevent setting delivery date in the past.

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


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

var currentdate = new Date(); //new creates an instance of an


object; new Date() without arguments,
creates a date object with the current
date and time
var deldate = g_form.getValue("u_delivery_date");
var date = new Date(deldate); //convert deliv date field value
into an object

if (date < currentdate) {


alert("Delivery date should be in the future.");
g_form.clearValue("u_delivery_date");
}

Create script to show alert box with current logged in user, set logged user as
caller and if category is software, make description field hidden.
alert("Current logged in user is: "+ g_user.getFullName());

g_form.setValue("caller_id", g_user.getFullName);
if(g_form.getValue("category")==software){
g_form.setVisible("description", false);
}

g_user – glide user is used to get current login details;


[Link]

Client script to auto populate email and phone number of requester via Referrence.

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


if (isLoading || newValue === '') {
return;
}
Ref table callback function
var requester = g_form.getReference("u_requested", getDetails);
function getDetails(requester) {
field value
g_form.setValue("u_email", [Link]);
g_form.setValue("u_phone_number", requester.mobile_phone);

}
}

If category is database, set description field as mandatory, put current user, incident number and
category into short description field.

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


if (isLoading || newValue === '') {
return;
}
if (g_form.getValue("category") == "database") {
g_form.setMandatory("description", true);
var test = g_user.getFullName() + " " +
g_form.getValue("number") + " " + g_form.getValue("category")
g_form.setValue("short_description", test);
}
else {
g_form.clearValue("short_description");
}

//Type appropriate comment here, and begin script below

}
If category is software and channel is phone then put alert box saying that you have selected the
category as software

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


if (isLoading || newValue === '') {
return;
}
if (g_form.getValue("category") == "software" &&
g_form.getValue("contact_type") == "phone") {
alert("The category is: "+ g_form.getValue("category") +" The
contact medium is: " +g_form.getValue("contact_type"))
}
//Type appropriate comment here, and begin script below

 On Submit

function onSubmit() {
var st = g_form.getValue("state"); //gets the value of State field
if (st == 8) { // is state is cancelled
var conf = confirm("You are about to cancel the incident. Are
you sure?");
if (conf) {
return true;
} else {
return false;
}
}

When description field empty, warn the user and don’t allow form submission.

function onSubmit() {
//Type appropriate comment here, and begin script below
if (g_form.getValue("description") == "") {
g_form.addErrorMessage("Description field cannot be empty");
return false; // or return 0;
}
}
3. Scripts – Background – opens a window where you can execute scripts on the server

Write a script that creates a record in Incident table with short description as test

var gr = new GlideRecord("incident"); // goes inside the incident table


[Link](); // same as clicking New to open a new record
gr.short_description = "test"; // populates the short description field with string
[Link](); // like clicking Save or Submit

Query: Runs the query against the table,Issue the query to the database to get relevant records.
In order to query a table, first create a ServiceNow object for the table. This object is called a
GlideRecord.
query() is a method of class 'GlideRecord'.

addQuery: Adds a filter to return records where the field meets the specified condition
Syntax: addQuery(String name, Object operator, Object value) //(field, operator, value).

Write a script that updates a record

var gr = new GlideRecord("incident"); // goes inside the incident table


[Link]("number", "INC0010024"); // like applying a filter on list search
(“field name”, “what we are looking for”)
[Link](); // like clicking Run
if([Link]()){ // if we know there is only one matching record then
no need to check if it exists; [Link]() is like going
inside of the record from search; if will only execute
if this happens
gr.short_description = "testing"; // updates the field
[Link](); // like clicking Update on record
}
[Link]() – returns all fields inside a record;

var gr = new GlideRecord("incident");


[Link]("number", "INC0010024");
[Link]();
while([Link]()){ //by using while we will update all tickets with this
number
gr.short_description = "testing";
[Link]();
}

Targeting a single record is better via Sys_ID

Write a script that deletes a record

var gr = new GlideRecord("incident");


[Link]("sys_id=57af7aec73d423002728660c4cf6a71c"); //for multi filters instead of
writing addQuery multiple
times you can just copy the
query from list search
[Link]();
if([Link]()){
[Link]();
}
4. Business rules

[Link] will NOT work in a BR. Use [Link] or [Link]. Log gets stored in log table
[Link] should NOT be used in BR. There is no point.
Two types of Business Rules:
 Before
 After

When making a new BR if you don’t select Advanced checkbox, it will be a Before rule.

If you want to access form fields with a BR you need to write:

current.field_name = “value we want” //if it’s a reference field value then we need sys_id

BEFORE example: //runs before going to the server; set field value before it gets
inserted into table

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

current.assignment_group = "0a52d3dcd7011200f2d224837e6103f2";

})(current, previous);
AFTER example: //runs after a request goes to the server; eg. Create a problem record when a
P1 incident gets opened; you cant create a PBM record before the incident is
created in the table

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

pbm = new GlideRecord("problem"); //goes into the problem table


[Link](); //creates a new record in problem table "New
button"
pbm.short_description = current.short_description; //sets problem
statement field
the same as short
description in
incident
[Link](); //save new problem record
[Link]("Problem record created: " + [Link]);//like
alert or
[Link]
gs - glide system

})(current, previous);

GlideSystem
The scoped GlideSystem (referred to by the variable name 'gs' in any server-side JavaScript) API
provides a number of convenient methods to get information about the system, the current
logged in user, etc.

Many of the GlideSystem methods facilitate the easy inclusion of dates in query ranges, and are
most often used in filters and reporting.

Gs. addInfoMessage(String message)


Gs. addErrorMessage(String message)
Gs. eventQueue(String name, Object instance, String parm1, String parm2, String queue)

gs is a global variable
Write a business rule that resolves all child incidents of a problem parent.

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

var gr = new GlideRecord("incident");


[Link]("problem_id", current.sys_id);
[Link]();
while ([Link]()) { // loop will go as long as there are records to
access
[Link] = 6; //6 is the Resolved state
gr.close_code = "Resolved by problem"; //mandatory field
population
gr.close_notes = "Resolved by problem" + [Link];
[Link]();
}
[Link]("All child incidents have been resolved");
})(current, previous);

Create a BR that creates a task in a child table once a record is opened on the
parent.

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

var gr = new GlideRecord("u_courier_task"); //open child


table
[Link](); // create new task
gr.u_status = current.u_status; // status child = status
parent
gr.u_courier = current.sys_id; // populate courier field
via sys id as it’s a reference
field
[Link]();
[Link]("Task " + gr.u_number + " created for ticket:
"+ current.u_number);

})(current, previous);
Write a BR that closes parent record (LIVE update, no refresh needed) once all
child records are closed.

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


//we start in task table
var parent = new GlideRecord("u_courier"); // go to courier table
if ([Link](current.u_courier) && parent.u_status != "closed")

// The 'get' method is used to return first record in the result set.
//we need to check whether current task has a parent or not
// if parent table returns a record with same number as child and the
status is not closed then execute

{
var child = new GlideRecord("u_courier_task"); //go to task
table
[Link]("u_courier", parent.sys_id); //filter child
records where parent reference field is same as current child

[Link]("u_status", "!=", "closed"); //filter where


status is not closed
[Link](); //runs query
if (![Link]()) { //if no record found
parent.u_status = "closed";
[Link](); // since it’s a BR it runs when updated
}

})(current, previous);
Business Rules

Business rules run server-side. They take information to and from the
server when they run on forms and lists. Not only that, but business rules
are major throughout the entire platform as they are configured to run
when a record is:

 Displayed
 Inserted
 Updated
 Deleted

And also:

 When a table is queried


 Before or after the database action has occurred
 Asynchronously!

Client Scripts

Client Scripts run…well, they run client-side, so there’s no phone call and
the changes happen in the user interface as they are made in the browser.
They run:

 Onchange()
o Runs when a particular field’s value changes.
 OnLoad()
o Runs when a page is loaded.
 OnSubmit()
o Runs when a record is submitted.
 OnCellEdit()
o Runs when a cell on a list changes value.

UI policies are client-side.

A UI policy is a rule that is applied to a form to dynamically change


information on the form. Then UI policy actions (the fun friend) determine
what happens on the form. For example, setting a field to mandatory or
requiring a value in order to save the record. (That’s my favorite part: so
much control over what the users can do *evil laugh*. Will I make them
have to fill it out or allow them to pass? Sorry, back to the policies…)

UI actions can be server or client-side depending on a checkbox.

They’re the buttons on lists and forms and the context menu.

Data policies run on the server-side and can be converted into UI


policies.

Data policy and UI policy can be a little confusing, so I try to remember


that data policy runs on the server-side and can be converted into UI
policy. Data policy acts whenever a record is inserted or updated into the
database by any means. UI policy runs on the client-side and acts
whenever a record is inserted/updated through a form.

5. UI Actions

Condition: current.u_status=="dispatched";
6. Calculated Value

- Go to form field Dictionary / Advanced view


- Tab calculated value – checkbox true

(function calculatedFieldValue(current) {

var email = current.u_requested.email;

return email; // return the calculated value

})(current);

- Changes are done once form is saved, not live!

7. Notifications
- System Notifications / Notifications
- When to send – decide if on inserd or on update etc
- Who will receive – users/ groups/ users groups in fields
- What it will contain

- Trigger Notification by event - EVENT Registration

o System / Event Registry


o Create Business Rule that fires the event

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


{
//(event name, object of the record where event is happening, to
which user)
[Link]("SendUpdateInProgress", current, current.caller_id);

})(current, previous);

o Create notification
 When to send – Event is Fired
 Advanced view
 Who will receive – Event parm 1 contains recipient =>
current.caller_id

- Scheduled jobs
o System Definition / Scheduled Jobs

var gr = new GlideRecord("incident");


[Link]("hold_reason=1");
[Link]();
while ([Link]()) {
[Link]("sendUpdateInProgress", gr, gr.caller_id);
}

- Fix script
o System Definition / Scripts – Background
o Difference between fix script and background script is that fix script is captured in
update set
o Changes done via fix script can be undone; script background is final so more
dangerous to use
var gr = new GlideRecord("incident");
[Link]("state=2^category=hardware^assignment_group!
=8a5055c9c61122780043563ef53438e3^ORassignment_group=NULL");
[Link]();
while([Link]()){
gr.assignment_group = "8a5055c9c61122780043563ef53438e3"; //sys_id of Hardware group
[Link]();
}
o System Definition / Fix Scripts
 You can add previous script here, export to XML and move to next instance
 On higher instance you import the xml and have the script ready for use

8. Update Sets

- What is captured in US:


o Tables
o Fields/Dictionaries
o UI Policise
o UI Actions
o UI Pages
o Client Scripts
o Business Rules
o Notifications
o Workflows

- What is NOT captured:


o Incidents
o Problems
o Changes
o Requests
o Request items
o Scheduled jobs
o User records
o Groups
o Any type of data record
- Moving Update Sets
o Instances need to be of the same version
o Once completed you can download an update set as a XML
o On higher instance you go to Retrieved Update Sets table where you can import the
US from lower instance
o First you need to Preview the US
o Once that is completed you can Commit US

- Update Sets sources


o System Update Sets / Update Sources
o Define a new connection to lower instance
o Retrieve Completed Update Sets
o Uploading a US via source automatically previews the US

- Update Sets Errors


o if there are errors you can view the differences between US content and current
instance
o you can decide to go with remote US or keep current and abandon
o
- Batch Update Sets
o Used to group multiple US and deploy them together
o These US have parent – child relation
o To create relation you go into the US record and populate Parent field
o Next move batch to higher instance and commit as a whole

9. Glide Query

The GlideQuery API is an alternative to GlideRecord to perform CRUD operations on record data from
server-side scripts.

The GlideQuery API lets you:

Use standard JavaScript objects and types for queries and results.
Quickly diagnose query errors with additional checks and clear error messages.
Simplify your code by avoiding boiler-plate query patterns.
Avoid common performance issues without needing deeper knowledge of GlideRecord.

GlideRecord returns ALL fields from a record which takes more time an traffic. GlideQuery only
returns fields we specify.
new GlideQuery("incident") // access incident table

.where("active",true) // set a fliter like addQuery

.select("number", "opened_at") // select fields to be queried

.forEach(function(gr) { // instead of while loop

[Link]([Link](gr));

});
…………………………………………………………………………………………………………………………………………………..
[Link]([Link](gr)); //prints all gr content

…………………………………………………………………………………………………………………………………………………..
new GlideQuery("incident")
.where("active", true)
.select("number", "state")
.forEach(function(gr) { // gr – any object can be used

[Link]("Incident: " + [Link] + " state: " + [Link]);

});

- Using “select” and “stream”

var users = [{name: "Abel"}, {name: "Mark"}, {name: "Paul"}] // define a table
[Link](function(gq) { // .forEach will iterate and select each element in the table
[Link]([Link]); // prints the name
});

new GlideQuery("sys_user")
.select() //when you dont give any parameter in select it will give unique value of the table
.forEach(function(user){
[Link](user.sys_id);
});
- Using “selectOne:

new GlideQuery("sys_user")
.where("last_name", "Admin")
.selectOne("first_name") // method to query a particular record
.ifPresent(function(user) { //method that prints values if any record is found

[Link](user.first_name);

});
var user = new GlideQuery("sys_user")
.where("last_name", "Tuter")
.selectOne("first_name") // will select first name field and unique value (always), here – sys_id
.orElse({first_name: "No user found"}) //if no user exists it will pring the message
[Link]([Link](user)); //[Link] is used to create a JSON string out of an object or
array; prints first name and unique value - sys_id
[Link](user.first_name); //prints first name field value or Else argument

var user = new GlideQuery("sys_user")


.where("last_name", "Tuter")
.selectOne("first_name")
.isPresent() //returns a boolean true or false
[Link]([Link](user)); // will return true or false

- Inserting a record with Glide Query

var gq = new GlideQuery("incident")


.insert({ //method to insert a record; need to provide json object as argument
short_description : "Record created using GQ",
state : 2 //value of In Progress state is 2
})
.get()
[Link]([Link](gq)) // will return:

*** Script:
{"sys_id":"3875eb9a97c5ca105f0c337e6253afdd","short_description":"Record
created using GQ","state":2}

- Updating a record with Glide Query


var gq = new GlideQuery("incident")
.where("sys_id", "24483bad97450a105f0c337e6253afca")
.update({
short_description : "Record updated by GQ" //once run it will update the record “LIVE”
})
var gq = new GlideQuery("incident")
.where("state", 2)
.updateMultiple({ //updateMultiple method is used
short_description : "Record updated by GQ"
})

- When a new normal change is opened create a task with same short description – Business
Rule with GlideQuery

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

new GlideQuery("change_task")
.insert({
change_request: current.sys_id,
short_description: current.short_description,
description: "Please follow change description"
})

})(current, previous);
10. SCRIPT INCLUDE. / Glide Ajax

- Reuseable code which can be called from any server-side script and client in some cases
- Used in:
o business rules,
o reference qualifiers,
o UI Actions
o other script includes
- Types of script includes:
o On demand/classless
o Extend an existing class
o Define a new class

Extend an existing class:


Var Classdemo = [Link](); [Link] =
[Link](AbstractAjaxProcessor, { typ: “Classdemo”});

Define a new class:


Var Classdemo = [Link](); [Link] = {initialize: function() {}, type:
“Classdemo” };

Glide Ajax is a class used by client-side script. It allows the execution of server side code from client
side. We should initialize the glide ajax with script include name as parameter which we want to use.
Parameter sysparm_name is used to find the function of script include we want to execute.
When we have to give custom parameter then we should remember that it should start with
sysparm.
Eg. [Link](“sysparm_assignedTo”, emp)

Glide Ajax has two types:


- Asynchronous – doesn’t wait for the response of the server. Uses callback function getXml()
- Synchronous – getXmWait()

Populate Email ID field based on selected Caller via script include.

1. Client script to get value of caller

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


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

var callerDetails = g_form.getValue("caller_id");


alert(callerDetails);

var ga = new GlideAjax("getEmailID"); //GlideAjax takes script


include name in brackets; goto script include and perform logic; so we
are inside the script include
//in script include we have a function email details that we need
to call here//

[Link]("sysparm_name", "emailDetails"); //add/pass a parameter


to emailDetails function
[Link]("sysparm_value", callerDetails); // pass value to the
SI function
[Link](getResult); //asynchronous call; callback function in
brackets
function getResult(response) { //response is coming from SI - email
var answer =
[Link]("answer"); //response
needs to be converted into this format; gives the value returned from
SI function
g_form.setValue("u_application_id", answer)
}
}

2. Script include to receive the value of caller.

var getEmailID = [Link]();


[Link] = [Link](AbstractAjaxProcessor, {
//extends an existing class

emailDetails: function() {
//we have to tell our SI that from client side are are tryin to
pass server side details
var test = [Link]("sysparm_value");
var x = new GlideRecord("sys_user"); //go to user table and
retrieve value of test
[Link]("sys_id", test);
[Link]();
if ([Link]()) {
return [Link]; //this email needs to be passed to client
side
}

},

type: 'getEmailID'
});
Populate location field based on selected user via script include and client
script.

1. Client script:

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


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

var ga = new GlideAjax('TestLocation');


[Link]('sysparm_name', 'getLocation'); //sys_parm is used to
read function from script include to
[Link]('sysparm_value', g_form.getValue('user_name')); //next
we have to send value selected on form to server side
[Link](test); //getXML is used to get the response from SI; in
brackets type a name for callback function
function test(res) { //the callback funtion is defined here
//whatever this function returns, it will go to line 9;
response is not in readable form so needs to be converted below
var answer =
[Link]("answer"); //details
received from return statement in script include is stored in res; this
returns sys_ID as its a reference field
g_form.setValue('user_location', answer)

}
}

2. Script Include
var TestLocation = [Link]();
[Link] = [Link](AbstractAjaxProcessor, {

getLocation:function(){
var getUser = [Link]('sysparm_value'); //receive
selected value; now need to check it in user table
var x= new GlideRecord('sys_user'); // go into user table
[Link]('sys_id', getUser);
[Link]();
if([Link]()){ //if it exists
return [Link]; //return location via dot walking
//now need to send this to client script via
getXML call
}

},

type: 'TestLocation'
});

How it works:
1. Return value from SI
2. Send I to the catalog client script with help of GlideAjax
3. Read value and send it back to server side
4. From server side we are getting a response
5. And from response we are setting the value CS

Send multiple values from script include to client side based on selected user.

- On change of caller (so onChange client script)

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


if (isLoading || newValue === '') {
return;
}
//first we need to get the value of Caller field
var callerDetails = g_form.getValue("caller_id"); //returns sys_id
//next we need to pass this value to server side with GlideAjax and
check the details
var ga = new GlideAjax('AutoPopulate_CallerInfo');
//with the help of GA we can go to script include side and see the
functions defined
[Link]('sysparm_name', 'getCallerInfo');
[Link]('sysparm_value', callerDetails); //selected caller is
passed to server side
//at this point server side returned required details
[Link](callback);

function callback(response) { //inside bracket we are passing


response

var answer =
[Link]('answer');
//this returns the email, sys_id of location, sys_id of
manager; we need to split this data
//Here "response" is an XML document which contains an
attribute "answer" and the value returned from the SI function binded
with the answer attribute.
var test = [Link](',');
//answer will be split in the form of array
g_form.setValue('u_caller_email', test[0]);
g_form.setValue('u_caller_location', test[1]);
g_form.setValue('u_caller_manager', test[2]);

}
}

var AutoPopulate_CallerInfo = [Link]();


AutoPopulate_CallerInfo.prototype =
[Link](AbstractAjaxProcessor, {

//first need to create a function


getCallerInfo:function(){

//we are passing the caller value via addParam and we have to read it
now
var sysIDcaller = [Link]('sysparm_value'); //sys_ID
//we have the sys_ID so we can go into user table and fetch info
var x = new GlideRecord('sys_user');
[Link]('sys_id', sysIDcaller);
[Link]();
if([Link]()){
return [Link]+','+[Link]+','+[Link];
//on server sie script is done; it returns xml or json so it needs to
be converted on client side

}, //make sure to put comma here

type: 'AutoPopulate_CallerInfo'
});

SAASSERVICENOW DEVELOPER TRAINING YT

Client side scripting:


- Client Scripts
- UI Policy
- UI Action
- UI Context Menus
- Validation Scripts
- Service Catalog UI Policy
- Ajax Client Scripts

Server side scripting:


- ACL
- Business Rule
- Ajax Server Scripts
- Script Actions
- Script Include
- Transform Map
- UI Action
- UI Context Menu
- Workflow Editor

Glide Classes:
- Server side Glide classes
o GlideRecord
o GlideElement
o GlideSystem
o GlideDateTime
o GlideAggregate
- Client side Glide classes
o GlideAjax
o GlideDialogWindow
o GlideForm
o GlideMenu
o GlideUser
o GlideList2

Script Execution Engine


- Before BR with order less than 1000
- Before Engine (Approvals, Data Policy, Field Normalization, Workflow)
- Before BR with order greater than 1000
- Database operation (Insert, Update, Delete)
- After BR with order less than 1000
- After Engines (table notification engine, update sync engine)
- Email notifications
- After BR with order greater than 1000

Macros
- vargr
- info

Client side scripting.

Client side scripts execute within a user’s browser and are used to manage forms and form fields.
Eg:
- Show alert when form loads
- Validate form data
- Show/hide choices on fields
- Hide/show section
- Set a value on the form
- Confirmation on submit
Client side API:
- GlideAjax
o Used to call server side code from client
o GlideAjax instance is called with GlideAjax constructor
o Used in Client scripting
o Syntax: var ga = new GlideAjax(<Script Include>)
- GlideFlow
o
- GlideForm
o Used to customize and perform activities on forms
o Object used to access GlideForm methods is g_form
o Used ONLY in Client
o Syntax: g_form.<GlideFormMethod>(Parameter)
- GlideDialogWindow
o Used for displaying a dialog in the current window and frame
o Used ONLY in Client
- GlideUser
o Used to get info about logged in user;
o Object used to access GlideUser methods is g_user
o Used ONLY in client
o Syntax: g_user.<GlideUserMethod()>
- GlideModal
- GlideList2
- GlideDocumentV3

Server side scripting.

Server side scripts execute on server and database. Eg


- Update a field when record is inserted
- Setting a value on a field when parent record is updated
- Validate the role of logged in user
- Generate events
- Send email

Server side API:


- GlideRecord
o Used for database operations
o Used ONLY in server side
o Syntax: var gr = new GlideRecord(TableName)
- GlideSystem
o Used to get information about system and current logged in user
o It is referred by a variable “gs”
o Syntax: gs.<GlideSystemMethod>()
- Glide Aggregate
o Used to perform aggregation operation on database
o An extension of the GlideRecord class
o Provides db aggregation (COUNT, SUM, MIN, MAX, AVG) queries
o Syntax: var agg = new GlideAggregare(TableName)
- GlideElement
- GlideDateTime

Client side scripting.

When a script will run:


- Onload
o Script will run when form loads and before control is given to the user
- onChange
o Script will run when value of a field is updated or changed
o Has parameters: control, oldValue, newValue, isLoading, isTemplate
- onSubmit
o Script will run when form is submitted or saved
o Used to perform validation before form is saved
- onCellEdit
o used only on Lists
o has parameters: sysIDs, table, oldValues, newValue, callback

Common API and Methods used in Client Scripts.

- GlideForm (g_form)
o addDecoration()
 show icon next to field
o addErrorMessage()
 show alert message to user
o addInfoMessage()
o addOption()
o clearOptions()
o clearValue()
o disableAttachments()
o enableAttachments()
o flash()
o getActionName()
o getBooleanValue()
 eg if checkbox is checked show an info message
o getControl()
 eg change color of text field
o getDecimalValue()
o getIntValue()
o getLabelOf()
o getReference()
o getSectionNames()
o getTableName()
o getUniqueValue()
o getValue()
o hideRelatedList()
o isLiveUpdating()
o isMandatory()
o isNewRecord()
o isSectionVisible()
o removeDecoration()
o removeOption()
o save()
o setDisabled()
o setDisplay()
o setLabelOf()
o setMandatory()
o setReadOnly()
o setSectionDisplay()
o setValue()
o showErrorBox()
o showFieldMsg()
o showRelatedList()
o submit()

- GlideUser (g_user)
o firstName
o getClientData
o getFullName
o hasRole
o hasRoleExactly
o hasRoleFromList()
o hasRoles()
o lastName()
o userID()
o username()

Debugging Client Scripts.


Tools for debugging client scripts:
- JavaScript Log
- Field Watcher
- Response Time Indicator
- Try/Catch of JavaScript

How to write a JS log


- Jslog() method is used to write to the JS log

UI Policy Scripts.

- Used to change the behavior of information on the form


- Runs at client side
- Primarily used to make fields read-only, visible or mandatory

Business Rules

Global variables of BR:


- Current
- Previous
- G_scratchpad
- gs
g_scratchpad – a good method when you need to fetch a field from the DB which cannot be done by
client script (except getRefference); used in Display BR

g_scratchpad.cLocation = current.caller_id.[Link]();

GlideSystem

What is Glide System?


- Object to access system level information
- Provides number of methods like:
o getUser()
o getUserName()
o getUserDisplayName()
o getUserID()
o hasRole()
- Runs on server side

GlideRecord

What is Glide Record?


- Object containing records
- Used for database operations
- Executed on server side mainly (but should be avoided due to performance issues)

Scheduled Job

What is Scheduled job?


- Automated part of logic which executes as a specific time and can be reoccurring with some
frequency
- Any action which needs to perform at a particular time can be automated with SJ
- Eg run a report, execute a script
- Cannot use current or previous
-
Script Include

What is Scheduled job?


- Store JS functions and execute on server side
- Can be re-used in different scripts
- Can be called from client scripts via GlideAjax
- Need to be called from another script

Types of Script Includes:


- Classless
o Only one reusable function
o Used to run on server side
o You don’t create any class
- Extend a class
o Adds functionality to another class
o Can be called from Client
- Utils
o New class
o Multiple functions
o Can be called from client

Script Include declaration:

<name of function>: function(){


Var userid = [Link](‘sysparm_user’); //sysparm is static; user can be anything
Var gr = new GlideRecord(‘sys_user’);

},

Calling SI from Client Script:

Var ga = new GlideAjax(‘name of script include’)


[Link](‘sysparm_name’, ‘<name of function in Script Include>’);
[Link](‘sysparm_<parameter name>’, <value to be stored in parameter>);
[Link](<callback function>);

Function <callback function>(response)


{
Var answer = [Link](“answer”);
<script to use value stored in answer>
}

Client callable SI that returns first and last name in alert box.

Script Include }

demotstFunc: function(){

var userid = [Link](‘sysparm_user’);

//any parameter from client will be stored here

Var gr = new GlideRecord(‘sys_user’);

//value from client will be searched on user table Client Script


to get first and last name

[Link](‘sys_id’, userid);
Var ga = new GlideAjax(‘demoTestAjax’);
[Link]();
[Link](‘sysparm_name’, ‘demoTstFunc’);
If([Link]()){
//calling function from SI
Var a = gr.first_name + gr.last_name;
[Link](‘sysparm_user’, newValue);
Return a;
//parameter to send to SI
//returns response
[Link](callBackFunction);

Function callBackFunction(response){
Var
answer=[Link]
[Link](‘answer’);
Alert(answer);
},

On problem form there should be a field Problem Owner and only users with problem_manager role
can be selected there. Server callable as adv reference qualifier.

Script Include
Refference qualifier
Getprbmanagers: function(){ Javascript:new <SI name>.<function name>
//first create function

Var pmanagers = ‘’; Javascript:new


prbFunctions().getprbmanagers()
//variable to store all sys_id of users with this
role
Var gr = new GlideRecord(‘sys_user_has_role’);

[Link](‘role’, ‘b573c1f95882300427dd’);

[Link]();

While ([Link]()){

Pmanagers = pmanagers +’,’ + [Link];

}
Var result = ‘sys_idIN’ + pmanagers;

Return result;

Mock interview questions:

Client Script Types


OnCell Edit –
OnSubmit –
Validate
UI Policy vs Data Policy –
UI Policy convert to Data Policy –
GlideRecord vs Glide Secure – glidesecure for sensitive data manipulation as it involves acl’s
Data Lookup –
Lookup rules – data lookup, assignment lookup, priority lookup
Fix Script –
Server side code – business rule, data policy, script include, script background, UI action
Update Set –
Glide Ajax –
Next and _next –
SLA retroactive – does the sla calculation from the past as well
Knowledge Article stages –
Knowledge auto publish –
Survey Designer –
Flow vs Action –
Notification –
G_scratchpad – user in display BR to call server side data to client side
Agile –
ATF –
Database view – A Database View is essentially a pseudo-table representing a join between several
contributing tables. The rows consist of combinations of contributing source records that share values
according to pre-indicated mappings.
Approval coordinator – for the legacy workflows
Export sets –
Cascading variables – Cascading allows values entered for variables in the initial order form to be
passed to the equivalent variables in the ordered catalog items. For example, a variable on the
initial order form prompts the customer to enter a delivery location value. If you enable cascading,
the value for this variable then populates delivery location fields on each of the ordered items.
Inbound action –
Event registry –
[Link] –
Incident matrix table ?
Query business?
Stages

You might also like