JavaScript Basics: Alerts, Loops, and Strings
JavaScript Basics: Alerts, Loops, and Strings
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
IndexOf
The indexOf() method returns the index of (the position of) the first occurrence of a
specified text in a string
The lastIndexOf() method returns the index of the last occurrence of a specified text
in a string:
Search
The search() method searches a string for a specified value and returns the position
of the match:
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).
*** Script: 45
SUBSTRING
*** Script: 45
SUBSTR
[Link](y)
[Link](y)
*** Script: I am learning scripting
[Link](y)
*** Script: I am learning ServiceNow
/i – makes it case insensitive
[Link](y)
*** Script: I am learning scripting scripting
/g – makes it a global match and replaces all
[Link](y)
*** Script: I am learning scripting scripting
/gi – you can combine both global match and case insensitive
CharAt
The charAt() method returns the character at a specified index (position) in a string:
[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).
[Link](0); // returns 72
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
str[0]; // returns H
FOR LOOP
WHILE LOOP
IF … ELSE …
var x = 6;
if (x%2 == 0)
{
[Link](x + " is even.");
}
else
{
[Link](x + " is odd.");
}
NESTED LOOPS
ARRAYS
[Link](cars[1]);
OBJECTS
…………………………………………………………………………………………………………………………………………….
[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" }
];
FUNCTIONS
var x = 2;
var y = 5;
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;
var a = 10;
var b = 20;
var x = 2;
var y = 5;
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 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 \nMy last name is Tyson"; // \n moves to next line
[Link](test);
SERVICENOW
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()
OnLoad
function onLoad() {
g_form.setValue("short_description", "testing if this works")
}
OnChange
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.
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);
}
Client script to auto populate email and phone number of requester via Referrence.
}
}
If category is database, set description field as mandatory, put current user, incident number and
category into short description field.
}
If category is software and channel is phone then put alert box saying that you have selected the
category as software
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
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).
[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.
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
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
})(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 is a global variable
Write a business rule that resolves all child incidents of a problem parent.
Create a BR that creates a task in a child table once a record is opened on the
parent.
})(current, previous);
Write a BR that closes parent record (LIVE update, no refresh needed) once all
child records are 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
})(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:
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.
They’re the buttons on lists and forms and the context menu.
5. UI Actions
Condition: current.u_status=="dispatched";
6. Calculated Value
(function calculatedFieldValue(current) {
})(current);
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
})(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
- 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
9. Glide Query
The GlideQuery API is an alternative to GlideRecord to perform CRUD operations on record data from
server-side scripts.
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
[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
});
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
*** Script:
{"sys_id":"3875eb9a97c5ca105f0c337e6253afdd","short_description":"Record
created using GQ","state":2}
- When a new normal change is opened create a task with same short description – Business
Rule with GlideQuery
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
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)
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:
}
}
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.
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]);
}
}
//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
type: 'AutoPopulate_CallerInfo'
});
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
Macros
- vargr
- info
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
- 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()
UI Policy Scripts.
Business Rules
g_scratchpad.cLocation = current.caller_id.[Link]();
GlideSystem
GlideRecord
Scheduled Job
},
Client callable SI that returns first and last name in alert box.
Script Include }
demotstFunc: function(){
[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
[Link](‘role’, ‘b573c1f95882300427dd’);
[Link]();
While ([Link]()){
}
Var result = ‘sys_idIN’ + pmanagers;
Return result;