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

Service Now Developer

The document provides an overview of ServiceNow development, focusing on scripting practices, particularly with GlideRecord and GlideAggregate APIs for database operations. It includes examples of method chaining and encoded queries, as well as details on dot walking and the GlideSystem API for logging and user management. Additionally, it highlights the importance of using correct field values in scripts and offers links to further resources and documentation.

Uploaded by

Sneha Malik
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)
111 views

Service Now Developer

The document provides an overview of ServiceNow development, focusing on scripting practices, particularly with GlideRecord and GlideAggregate APIs for database operations. It includes examples of method chaining and encoded queries, as well as details on dot walking and the GlideSystem API for logging and user management. Additionally, it highlights the importance of using correct field values in scripts and offers links to further resources and documentation.

Uploaded by

Sneha Malik
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
You are on page 1/ 119

Service Now Developer

NOTE:-

While you are working with scripts, labels are not used instead their values are used. For example

Current.incident_state==”closed” is not valid

Current.incident_state==7 is a valid argument

https://www.servicenow.com/docs/bundle/xanadu-servicenow-platform/page/product/service-catalog-
management/task/create-request-from-other-flow.html
I am using a scheduled job called find overdue task after executing which and event is triggered, that
triggered event generates a notification email, I can see that email in emails module as status send-ready,
but cant see it on guirella mail.
2. I am sending an email to my pdi mail but the mail is wrong it is saying.
Create an item variable asignment
Breakdown source in dashboard
Now assist in catalog builder
Catalog conversational coverage
Lecture 15 :- workflow scripting
Assigned_to field has no value error
scriptdebugger
Console.dir()
https://docs.servicenow.com/bundle/vancouver-now-intelligence/page/use/reporting/concept/function-fields-
reporting.html
https://docs.servicenow.com/bundle/vancouver-now-intelligence/page/use/reporting/concept/
c_GenerateReports.html
……………………………

For a list of additional ServiceNow resources, checkout this page: https://www.markmmiller.com/resources


For a list of common FAQs to my courses, checkout this page: https://www.markmmiller.com/faqs.
There are almost 30 locations in servicenow where we can do scripting
Eg :- script includes, business rules, client side , server side, ui action, workflow, ui policies, ui maps, transform
maps etcc
GlideRecord API – business rules, ui action, script include

NOTE
The sys_attachment table contains the meta data about the attachment files and the sys_attachment_doc table
contains the actual file data.

"When you store an attachment to any table, a record is created in the Attachment [sys_attachment] table that
contains attachment metadata. The file data is stored in the Attachment Document [sys_attachment_doc] table,
in 4k chunks. For example, if you attach a 12k file called My_attachment.pdf, then there is an Attachment entry
with three related Attachment Document entries."
Glide Record Api
The GlideRecord API is a powerful scripting tool in ServiceNow that allows developers to interact with
database records programmatically. It provides methods to create, read, update, and delete records in
ServiceNow tables. Here’s a comprehensive overview of the GlideRecord API based on the ServiceNow
documentation.
When you apply a filter on any table in ServiceNow, such as the incident table, the platform uses the
GlideRecord API behind the scenes to construct and execute the appropriate database queries.
How GlideRecord Works with Filters
1. User Interface Interaction:
o When a user applies a filter on a table (e.g., filtering incidents by state or priority), the
ServiceNow platform captures the filter conditions specified by the user.
2. GlideRecord Usage:
o Behind the scenes, ServiceNow translates these filter conditions into GlideRecord calls. For
example, if a user wants to see all active incidents, the platform will construct a GlideRecord
query that resembles the following:
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.query();
while(gr.next()){
gs.print(gr.number); //gs.print() is used to print to screen(gs = glidesystem)
}
here, we are creating a gliderecord object gr from the constructor.
o This GlideRecord instance queries the database for records that match the specified conditions.
3. SQL Query Generation:
o Although ServiceNow uses an SQL database to store data, users and developers do not need to
write raw SQL queries. Instead, GlideRecord abstracts the complexity of SQL, allowing
developers to work with high-level JavaScript syntax.
o The GlideRecord API translates these high-level queries into SQL queries that the database
understands. For instance, the above GlideRecord code might generate an SQL query like:
SELECT * FROM incident WHERE active = true;
4. Result Processing:
o After executing the query, GlideRecord retrieves the matching records from the database.
Developers can then iterate through the results using the next() method and access the data using
methods like getValue() or setValue().

Overview of GlideRecord
 Purpose: GlideRecord is primarily used for database operations on tables within the ServiceNow
platform. It allows you to manipulate records and perform CRUD (Create, Read, Update, Delete)
operations.
 Initialization: You create a GlideRecord object for a specific table by passing the table name to the
constructor. For example:

var gr = new GlideRecord('incident');

Key Methods of GlideRecord

 Method  Description

 addQuery  Adds a condition to the query.

 addQuery(fieldName, value)  Adds a condition based on a field name and its value.

 addQuery(fieldName, operator,
 Adds a condition based on a field name, operator, and value.
value)

 addOrCondition  Adds an OR condition to the query.

 query  Executes the query against the database.

 next  Moves to the next record in the result set. Returns boolean

 get  Retrieves a single record by sys_id.

 getValue  Retrieves the value of a specific field.

 Checks if the GlideRecord is valid (i.e., if a record was


 isValidRecord
found).

 initialize  Prepares a new record for insertion.

 setValue  Sets the value of a specific field.

 Inserts the new record into the database and returns the new
 insert
sys_id.

 update  Updates the current record in the database.

 deleteRecord  Deletes the current record from the database.

 Returns a Boolean value indicating whether the next record


 hasNext
exists.

 Orders the result set in ascending order based on the specified


 orderBy(‘fieldname’)
field name.

 Orders the result set in descending order based on the


 orderByDesc(‘fieldname’)
specified field name.

 Adds an encoded query string to the GlideRecord for more


 addEncodedQuery
complex queries.

 Returns a Boolean value indicating if the current user has


 canCreate
permission to create a new record in the specified table.

 Returns a Boolean value indicating if the current user has


 canDelete
permission to delete a record in the specified table.

 canRead  Returns a Boolean value indicating if the current user has


 Method  Description

permission to read a record in the specified table.

 Returns a Boolean value indicating if the current user has


 canWrite
permission to write a record in the specified table.

 addNullQuery  Adds a query for fields that are NULL.

 addNotNullQuery  Adds a query for fields that are not NULL.

 Returns the name of the table for the current GlideRecord


 getTableName
object.

 Returns the encoded query string representing the current


 getEncodedQuery
state of the GlideRecord object.

 Retrieves aggregate values from the database based on


 getAggregate
specified conditions (e.g., COUNT, SUM).

NOTE:-
 Operators in addQuery() can be :- =, !=, >, <, >=, <=, LIKE, IN, STARTSWITH, ENDSWITH, NOT
IN, IS EMPTY, IS NOT EMPTY, BETWEEN, ON, AFTER, BEFORE.
 incidentGR.addNotNullQuery('short_description'); // Add a condition where short_description is not
null
 incidentGR.addNullQuery('sub_category’); // Add a condition where 'sub_category’ is null
 get can accept one argument as sys_id, or 2 arguments where one being the filedname and fieldvalue
 setLimit() :- is used to limit the number of output we want. setLimit(5) will show only top 5 records.
 getRowCount()

 To add a new record using GlideRecord API


var incidentGR = new GlideRecord('incident');
incidentGR.initialize();
incidentGR.setValue('short_description', 'New incident created through GlideRecord');
var newSysId = incidentGR.insert();
gs.print('New incident created with sys_id: ' + newSysId);
 var incidents = [];
var counter = 1;
var gr = new GlideRecord('incident');

while(counter<=5){
gr.initialize();
gr.short_description ='Incident' + counter;
counter++;
incidents.push(gr.insert());
gs.print(incidents);
}
 canRead() :- The canRead() method in GlideRecord is used to determine if the current user has
permission to create a read record in the specified table. Returns a Boolean value.
 canWrite () :- The canWrite () method in GlideRecord is used to determine if the current user has
permission to write a new record in the specified table. Returns a Boolean value.

In ServiceNow, you can query records using the GlideRecord API in two primary ways: method chaining and
encoded queries. Each method has its advantages and can be used depending on your specific use case and
coding preferences.
1. Method Chaining
Method chaining involves calling multiple methods in a single statement to build your query. This approach is
more readable and allows you to define your query step by step. Here's how it works:
Example
var incidentGR = new GlideRecord('incident');
var cond1 = incidentGR.addQuery('priority', '1');
cond1.addOrQuery('priority', '2'); // Use straight quotes for strings

var cond2 = cond1.addQuery('state', 'new');


cond2.addOrQuery('state', 'in progress'); // Use straight quotes for strings
cond2.addQuery('opened_at', '>', '2020-09-21'); // Use the correct field name for date
incidentGR.query(); // Execute the query

// Process the results


while (incidentGR.next()) {
gs.info('Incident Number: ' + incidentGR.number);
}Key Points of Method Chaining
 Readability: The code is more structured and easier to read as each query condition is clearly defined.
 Flexibility: You can easily add, modify, or remove conditions as needed.
 Execution: After defining all the conditions, you call the query() method to execute the query.
2. Encoded Queries
Encoded queries are string-based queries that use a specific syntax to define the conditions. This method is
useful when you want to write a complex query in a single line, especially when there are many conditions.
We can copy these encoded queries from the breadcrumbs.
Example
var incidentGR = new GlideRecord('incident'); // Create a GlideRecord for the incident table
incidentGR.addEncodedQuery('priority=1^state=open'); // Use encoded query syntax
incidentGR.orderBy('sys_created_on'); // Order results by the creation date
incidentGR.query(); // Execute the query
while (incidentGR.next()) { // Loop through the results
gs.info('Incident Number: ' + incidentGR.number);
}
Key Points of Encoded Queries
 Conciseness: Encoded queries allow you to define complex conditions in a compact form.
 Syntax: The syntax uses ^ to represent "AND" conditions and ^OR for "OR" conditions. For example,
priority=1^state=open means "priority is 1 AND state is open."
 Complex Queries: They are particularly useful for more complex queries involving multiple AND/OR
conditions.
When to Use Which Method
 Method Chaining: Ideal for scenarios where you have a moderate number of conditions and want your
code to be easily readable and maintainable.
 Encoded Queries: Best suited for more complex queries that involve multiple conditions, especially
when you want to keep your code compact.
NOTE:-
 Running gr.query() is important.
var gr = new GlideRecord('incident');
gr.query();
while(gr.next()){
gs.print(gr.number); or gs.print(gr.caller_id) etc etc
}
 Will only print the first record
var gr = new GlideRecord('incident');
gr.query();
gr.next();
gs.print(gr.number);
 Will only print nothing
var gr = new GlideRecord('incident');
gr.query();
gs.print(gr.number);
var gr = new GlideRecord('incident');
gr.addQuery('priority', '1');
gr.query();
while(gr.next()){
gs.print('Incident' + gr.number + 'Priority' + gr.priority + " : " +
gr.priority.getDisplayValue() );
}
OUTPUT :-
*** Script: IncidentINC0000009Priority1 : 1 - Critical
.

 var gr = new GlideRecord('incident');


gr.orderBy('short_description');
gr.query();
while(gr.next()){
gs.print('Incident' + gr.short_description );
}

glideRecordSecure
has same methods as glideRecord() but here we don have to add additional checks, canCreate(), canUpdate()
etc If the user don’t have access the script wont execute.
GlideAggregate is a powerful class in ServiceNow that allows you to perform aggregate queries on tables, such
as counting records, calculating sums, averages, and more. It provides a way to efficiently gather summarized
data from the database without retrieving all the individual records, which can improve performance and reduce
load on the server.
It is almost same as glideRecord but It has aggregate methods as well
Key Features of GlideAggregate
 Aggregate Functions: Supports various aggregate functions like count(), sum(), average(), min(), and
max().
 Group By: Allows you to group results based on specific fields, similar to SQL's GROUP BY clause.
 Efficiency: Returns summary data, minimizing the amount of data sent over the network, which can
lead to better performance.
var ga = new GlideAggregate('incident');
ga.addQuery(‘sys_created_on’, ‘date’);
ga.addAggregate('COUNT'); // Count the number of incident records
ga.query();
if (ga.next()) {
gs.info('Total Incidents: ' + ga.getAggregate('COUNT'));
}

Dot Walking
Dot walking is a powerful feature in ServiceNow that allows users and developers to traverse related records
and access field values across relationships using a simple dot notation. This functionality is particularly useful
in scripts and business rules where you want to access fields from related tables without writing complex
queries or logic.
How Dot Walking Works
In ServiceNow, many tables have relationships, often defined through reference fields. For example, the
incident table has a reference to the caller (which is usually a user record). Dot walking lets you access fields
from the caller record directly from an incident record using dot notation.
Syntax and Usage
The syntax for dot walking is straightforward. Here’s the general structure:
record.reference_field.field_name
Where:
 record is a GlideRecord object representing the current record.
 reference_field is the name of the field that contains the reference to another record.
 field_name is the field you want to access from the referenced record.

EG:-
var incidentGR = new GlideRecord('incident'); // Create a GlideRecord for the incident table
incidentGR.get('incident_sys_id'); // Fetch a specific incident by its sys_id

while (incidentGR.isValidRecord()) { // Check if the record is valid


gs.print(incidentGR.caller_id.location.name);
}

 incidentGR.caller_id: Accesses the caller reference field in the incident record, which points to a User
record.
 location: This is a reference field in the User record that points to the user's location.
 name: This accesses the name field of the location record.
glideSystem API
The GlideSystem (often abbreviated as gs) is a ServiceNow API that provides various utility methods for
interacting with the ServiceNow platform, particularly for scripting in Business Rules, Script Includes, and
other server-side scripts. It allows developers to interact with system properties, manage logging, and work with
dates and times, users, and more.
Method Description Example Usage

Logs a custom message with


gs.log(message, source) gs.log("Message", "ScriptName");
an optional source label.

Logs an informational
gs.info(message) gs.info("Info message");
message.

gs.warn(message) Logs a warning message. gs.warn("Warning message");

gs.error(message) Logs an error message. gs.error("Error message");

Returns the current user as a


gs.getUser() var user = gs.getUser();
GlideUser object.

Returns the username of the


gs.getUserName() var username = gs.getUserName();
current user.

Returns the display name of var displayName =


gs.getUserDisplayName()
the current user. gs.getUserDisplayName();

Returns the current date and


gs.now() time in GMT as a var currentTime = gs.now();
GlideDateTime object.

Returns the current date and


gs.nowDateTime() var currentDateTime = gs.nowDateTime();
time in GMT as a string.

Returns the current date as a


gs.today() var todayDate = gs.today();
GlideDate object.

Returns the date a specified


gs.daysAgo(days) var dateAgo = gs.daysAgo(5);
number of days ago.

Retrieves a system property by


gs.getProperty(propertyName, var prop = gs.getProperty("my.prop",
name with an optional default
default) "default");
value.

Sends an email with specified gs.email("[email protected]",


gs.email(to, from, subject, body) to/from addresses, subject, and "[email protected]", "Subject",
body. "Body");

gs.eventQueue(eventName, record, Triggers an event for gs.eventQueue("event.name", current,


parm1, parm2) processing. "param1", "param2");

Checks if the current user has a


gs.hasRole(roleName) if (gs.hasRole("admin")) { ... }
specific role.

Retrieves the GlideSession


gs.getSession() var session = gs.getSession();
object for session-level info.

gs.generateGUID() Generates a unique globally var guid = gs.generateGUID();


Method Description Example Usage

unique identifier (GUID).

Adds an informational
gs.addInfoMessage(message) gs.addInfoMessage("Info message");
message to the UI.

Adds an error message to the


gs.addErrorMessage(message) gs.addErrorMessage("Error message");
UI.

Checks if a given value is null


gs.nil(value) if (gs.nil(current.email)) { ... }
or undefined.

Note ;-
 The gs.log() method in ServiceNow includes an optional source parameter to help identify the origin or
context of a log message. This is particularly useful in complex environments where multiple scripts,
business rules, workflows, or applications may generate logs. The source parameter makes it easier to
trace and troubleshoot issues by specifying which part of the system the log message came from.
 Identifying the Origin of Logs: When you specify a source, it tags the log entry with the given
identifier, allowing administrators and developers to quickly understand where the log entry originated.
 gs.log(), gs.warn(), gs.error() can be seen in logs, warn, error under system log module.
 gs.beginningOfLastMonth()
 getUser() returns an object
 if(gs.hasRole('itil') || gs.hasRole('admin')){
gs.print('the current role is either itil or admin');
}
 gs.tableExitsts()

glideForm
The GlideForm (g_form) API in ServiceNow provides a way to interact with form fields and manage form
behavior on the client side. It’s commonly used in Client Scripts and UI Policies to control the user interface
dynamically, based on certain conditions or field values. This API is essential for customizing forms, guiding
users through data entry, and improving user experience.
Method Description

g_form.setValue(fieldName, value) Sets the value of a specified field.

g_form.getValue(fieldName) Retrieves the current value of a specified field.

g_form.setVisible(fieldName, visible) Shows or hides a specified field based on a boolean value.

Similar to setVisible, but maintains space for the hidden


g_form.setDisplay(fieldName, visible)
field if set to false.

g_form.setReadOnly(fieldName, readOnly) Makes a specified field read-only or editable.

g_form.addInfoMessage(message) Adds an informational message at the top of the form.

g_form.addErrorMessage(message) Adds an error message at the top of the form.

g_form.setMandatory(fieldName, mandatory) Marks a field as mandatory or optional.

g_form.focus(fieldName) Sets the focus to a specified field on the form.

g_form.isMandatory(fieldName) Checks if a field is marked as mandatory.

g_form.isModified() Checks if any field on the form has been modified.

g_form.save() Saves the form without navigating away from the page.

g_form.submit() Submits the form, similar to clicking the "Save" button.

g_form.addOption(fieldName, choiceValue,
Adds a new option to a choice field.
choiceLabel)

g_form.removeOption(fieldName, choiceValue) Removes a specified option from a choice field.

g_form.clearValue(fieldName) Clears the value of a specified field.

g_form.clearMessages() Clears any messages displayed at the top of the form.

g_form.getLabelOf(fieldName) Retrieves the label of a specified field.

g_form.getSectionNames() Returns the names of all sections on the form.

g_form.getFieldNames() Retrieves all field names present on the form.

 hideRelatedLists()
 showRelatedLists()
 isMandatory(‘fieldname’)
 getLbaleOf(‘fieldname’);

 getReference()

The getReference() method in the GlideForm (g_form) API is used to retrieve a reference record for a field
that holds a reference to another table. This is especially useful for fetching related data from referenced records
on a form without requiring an extra server call. It is commonly used with fields that contain references, such as
the caller field on an Incident form (which references the User [sys_user] table).
Syntax
1. Using getReference with a Callback
 What it Does: Fetches the referenced record asynchronously and executes the provided callback
function once the data is retrieved.
 Why Use It: Ideal for avoiding UI performance issues since the script doesn't block execution while
waiting for the data.

2. Using getReference Without a Callback


 What it Does: Fetches the referenced record synchronously, causing the script to wait until the record
is retrieved.
 Why Use It: Not recommended because it can lead to poor UI performance or browser timeouts,
especially for slow network connections.

Example Usage
Let’s say you want to retrieve the full name and email of the user referenced in the caller field on an incident
form:
g_form.getReference('caller_id', function(callerRecord) {
if (callerRecord) {
var fullName = callerRecord.name;
var email = callerRecord.email;
g_form.addInfoMessage('Caller Name: ' + fullName + ', Email: ' + email);
}
});
In this example:
 caller_id is the reference field pointing to the User [sys_user] table.
 Once the record is fetched, the callback function accesses the name and email fields of the callerRecord
object and displays them as an informational message.
Notes
 Since getReference() is asynchronous, any code that depends on the retrieved data should be within the
callback function.
 This method is particularly useful for client-side logic that requires data from referenced records without
needing an extra GlideRecord call on the server side.
glideUser()
the glideUser() api is used to access information about the current user and current user roles. Using glideUSer
api avoids the need to use the slower glideRecord api to get user information.
The GlideUser (g_user) API in ServiceNow provides access to information about the currently logged-in user.
This API is primarily used in Client Scripts to retrieve details like the user’s name, roles, company, and
language, and to perform checks based on their role or user ID.

Eg :-
var hasItil = g_user.hasRole('itil');
if(!hasItil({
alert(' role is not itil');
}

 hasRole() and hasExactRole() are 2 diff things ( consider g_user is an admin)


console.log(g_user.hasRole(‘catalog_admin’)); //returns true
console.log(g_user.hasExactRole(‘catalog_admin’)); //returns false

Method Description

g_user.getUserID() Returns the user ID of the currently logged-in user (e.g., sys_id).

g_user.getUserName() Returns the username of the currently logged-in user.

g_user.getFullName() Returns the full name of the currently logged-in user.

g_user.hasRole(role) Checks if the user has a specific role. Returns true or false.

Checks if the user has any roles. Returns true if they have one or
g_user.hasRoles()
more roles, false otherwise.

Checks if the user has exactly the specified role, ignoring inherited
g_user.hasRoleExactly(role)
roles.

g_user.getCompanyID() Returns the sys_id of the company associated with the user.

g_user.getEmail() Returns the email address of the currently logged-in user.

g_user.getDepartmentID() Returns the sys_id of the department associated with the user.

g_user.getLocationID() Returns the sys_id of the location associated with the user.

g_user.getPreference(name) Retrieves a specific user preference by name.

g_user.savePreference(name,
Saves a user preference with a given name and value.
value)

g_user.isMemberOf(group) Checks if the user is a member of a specified group. Returns true or


Method Description

false.

g_user.getRoles() Returns an array of roles assigned to the user.

g_user.getLanguage() Returns the language set for the current user (e.g., en, fr).

Note :-
In the Xanadu release of ServiceNow, the GlideUser (g_user) API introduced direct property access for
certain user attributes, making it one of the few APIs in ServiceNow with this capability. This means you can
access properties like g_user.firstName, g_user.lastName, and g_user.roles directly.

GlideAjax
GlideAjax is a powerful feature in ServiceNow that enables client-side scripts to call server-side scripts
asynchronously. It allows for efficient data retrieval and processing without reloading the page, improving the
user experience and reducing the load on the client side. Here’s a summary of how GlideAjax works and some
of its common uses:
1. Setting Up GlideAjax:
o First, create a script include on the server side to define what data should be returned. The script
include needs to be "Client Callable," allowing it to be accessed by GlideAjax.
o GlideAjax is then used on the client side to make an asynchronous call to this script include,
sending necessary parameters and handling the server's response.
2. Using GlideAjax in Client Scripts:
o A GlideAjax call is initiated on the client side by creating a new GlideAjax object and passing
the name of the server-side script include.
o You can add parameters using the addParam() method, then execute the query with the
getXML() or getXMLAnswer() method to process the response.
o The getXMLAnswer() function is typically used to handle simple text responses, while
getXML() can handle more complex XML-based data.
3. Advantages and Use Cases:
o GlideAjax is particularly useful for real-time data retrieval without a full-page refresh, such as
fetching details for a selected record or dynamically updating fields based on other field values.
o It’s commonly used for user role checks, validation of data, or dynamically loading related
information based on field selection.
Here's how addParam() works:
1. Method Signature:
o addParam('sysparm_name', 'value')
o The method takes two arguments: the parameter name (sysparm_name) and its value.
 getXML(): This returns the complete XML response from the server, allowing access to elements
within the XML.
 getXMLAnswer(): This retrieves only the value of the answer attribute in the response XML, making
it a convenient way to access single values
1. "Has access to any variable starting from sysparam_"
 In ServiceNow’s GlideAjax, any client-side parameter prefixed with sysparm_ (like sysparm_name,
sysparm_id, etc.) is passed to the server-side script include. These sysparm_ parameters can be accessed
in the server script as variables by calling the getParameter() method. For example:
var paramValue = this.getParameter('sysparm_id');
 This is a standardized way of sending parameters from the client script to the server, ensuring they can
be reliably accessed in the script include.
2. "Use sysparam_name to invoke method in script include"
 In GlideAjax, the sysparam_name parameter is used specifically to indicate which method in the script
include should be called. By setting sysparam_name to the name of the method (e.g.,
ga.addParam('sysparam_name', 'sayHello');), ServiceNow identifies and runs that method in the script
include. This is how GlideAjax determines which function within a script include should handle the
request, especially when multiple methods exist in the same script include.
Example in Context:
 Client Script:
var ga = new GlideAjax('MyScriptInclude');
ga.addParam('sysparam_name', 'sayHello');
ga.addParam('sysparam_userId', '12345');
ga.getXML(function(response) { // getXMLAnswer() or getXML() takes a callback
function, which will be called after receiving response
from server
var result = response.responseXML.documentElement.getAttribute("answer");
alert(result);
});
OR
ga.getXML(ajaxCallback);
function ajaxCallback(response){
var result = response.responseXML.documentElement.getAttribute("answer");
alert(result);
}
 Script Include (MyScriptInclude):
var MyScriptInclude = Class.create();
MyScriptInclude.prototype = Object.extendsObject(AbstractAjaxProcessor, {
sayHello: function() {
var userId = this.getParameter('sysparam_userId'); // Accessing the 'sysparam_userId' variable
return 'Hello, user ' + userId;
},
type: 'MyScriptInclude'
});
In this setup, sysparam_name is set to sayHello, meaning the sayHello function in MyScriptInclude will be
executed, and sysparam_userId is accessed within that function.

 Difference between getXML and getXMLAnswer()

ga.getXML(function(response) {
var xmlDoc = response.responseXML.documentElement.getAttribute(“answer”);
console.log(xmlDoc);

AND

ga.getXMLAnswer(function(answer) {
console.log(answer); // Directly logs the answer attribute's value
});

When working with GlideAjax in ServiceNow, the request/response process generally consists of three stages:
1. Request Initialization (Client-Side)
 This is where the client script creates a GlideAjax object, specifies the script include to call, and adds
any parameters required by the server-side method. The client script uses addParam() to pass
parameters, including sysparam_name to specify the server-side function.
 Once set up, the client initiates the request with getXML() or getXMLAnswer(), which sends the
request to the server asynchronously.
2. Server-Side Processing
 The request reaches the specified script include on the server side, where ServiceNow retrieves the
method named in sysparam_name. The server executes this method and processes any parameters
provided in the request.
 The method can access these parameters using this.getParameter('sysparam_name'), and it will perform
the necessary data retrieval or computation. Finally, it prepares a response, which is returned in XML
format to the client.
3. Response Handling (Client-Side)
 The response is received by the client in XML format. If getXMLAnswer() was used, it extracts only the
value of the answer attribute in the XML, while getXML() provides the full XML response.
 A callback function processes the response, updating the UI or handling data as needed on the client side
without refreshing the page.
glideDateTime
The GlideDateTime and GlideDate APIs in ServiceNow serve different purposes when handling date and time
values:
1. GlideDateTime: This class is used to manage both date and time components, providing high precision
(up to milliseconds). It is ideal for scenarios where you need to account for the exact time, such as
scheduling tasks, logging timestamps, or making precise comparisons between two date-time values.
GlideDateTime also offers methods for time manipulation (e.g., addSeconds(), subtract()) and supports
time zone handling
ServiceNow
.
2. GlideDate: In contrast, GlideDate focuses solely on date management, ignoring any time component.
This makes it suitable for operations that only concern dates, such as comparing birthdates or due dates
where time is irrelevant. GlideDate methods include operations like addDays() and subtract()
ServiceNow
.
When to Use Each
 Use GlideDateTime when:
o You need to include both date and time in your logic.
o Precise time comparisons are required.
o Your application handles tasks across multiple time zones.
 Use GlideDate when:
o You only care about the date part.
o Time of day is not a factor in your application logic.

Method Description

addDays(days) Adds a specified number of days to the date/time object.

addHours(hours) Adds a specified number of hours to the date/time object.

addMinutes(minutes) Adds a specified number of minutes to the date/time object.

addSeconds(seconds) Adds a specified number of seconds to the date/time object.

Subtracts another GlideDateTime object from the current object and returns the
subtract(GlideDateTime)
difference.

getDayOfWeek() Returns the day of the week (1-7, where 1 is Sunday).

getDate() Returns the date portion of the GlideDateTime object.

getTime() Returns the time portion of the GlideDateTime object.

getDisplayValue() Returns the date/time in a user-friendly format.

getLocalTime() Returns the date/time adjusted to the local time zone.


Method Description

getUTCTime() Returns the date/time in UTC (Coordinated Universal Time).

setDisplayValue(value) Sets the date/time from a formatted string value.

isValid() Checks if the date/time object is valid.

getParameter(paramName) Retrieves a parameter value from the date/time object, if applicable.

setTZ(timezone) Sets the time zone for the GlideDateTime object.

toString() Returns the string representation of the GlideDateTime object.

getEffectiveDisplayValue() Returns the effective display value considering the user's locale and time zone.

Eg
1.
var gd1 = new GlideDateTime();
gs.print(gd1);

var gd2 = new GlideDateTime();


gd2.setValue('2024-10-24 00:00:00');
gs.print(gd2);

var diff = GlideDateTime.subtract(gd1, gd2);


gs.print(diff.getDisplayValue());

output :-
***Script:2024-10-2910:46:04
***Script:2024-10-24

2.
var gd1 = new GlideDateTime();
gd1.addDaysUTC(3);
gs.print(gd1);

before() Method

 Purpose: The before() method is used to determine if one GlideDateTime object represents a date and
time that occurs before another GlideDateTime object.
after() Method
 Purpose: Conversely, the after() method checks if one GlideDateTime object occurs after another
GlideDateTime object.

var date1 = new GlideDateTime('2024-10-24 00:00:00');


var date2 = new GlideDateTime(); // Current date and time

if (date1.before(date2)) {
gs.info('Date1 is before Date2');
}

if (date2.after(date1)) {
gs.info('Date2 is after Date1');
}

CompareTo() :- it return -1, 0, 1 as answer


var date1 = new GlideDateTime('2024-10-24 00:00:00');
var date2 = new GlideDateTime(); // Current date and time
var comparison = date1.compareTo(date2);
if (comparison < 0) {
gs.info('Date1 is before Date2'); }
else if (comparison > 0) { gs.info('Date1 is after Date2'); }
else { gs.info('Date1 is the same as Date2'); }

GlideElement API
The GlideElement API in ServiceNow is a powerful tool used to interact with fields in GlideRecord objects. It
provides methods to manipulate, validate, and retrieve information from individual fields within a record. Here
are some key functionalities and methods associated with GlideElement:
Key Features of GlideElement
1. Field Manipulation: You can set or get values of fields within a record using GlideElement. This
allows for easy data manipulation during script execution.
2. Value Validation: GlideElement provides methods to validate field values, ensuring that data entered
into fields meets specific criteria or formats.
3. Field Attributes: The API allows you to retrieve attributes related to fields, such as whether a field is
mandatory or read-only.
Common Methods
Here are some commonly used methods in the GlideElement API:
 getValue(): Retrieves the current value of the field.
 setValue(value): Sets the value of the field to the specified value.
 getDisplayValue(): Returns the display value of the field, which may be formatted differently than the
stored value.
 isMandatory(): Checks if the field is mandatory.
 isNull(): Checks if the field has no value (is null).
 getHTMLValue() :- return html
 getJournalEntry(-1)

Eg:-
1.
var gr = new GlideRecord('incident');
if (gr.get('sys_id', 'your_incident_sys_id')) { // Replace with actual sys_id
var shortDesc = gr.short_description; // GlideElement for 'short_description'
gs.info('Short Description: ' + shortDesc.getValue()); // Using getValue()

// Setting a new value


shortDesc.setValue('Updated short description');
gr.update(); // Save the changes to the record
}
2.
var gd = new GlideRecord('incident');
gd.get('dfa0dd19c3251210a7c3be13e4013198');
gs.print(gd.caller_id.getDisplayValue());

3.
var gd = new GlideRecord('kb_knowledge');
gd.get('409de43187032100deddb882a2e3ecd9');
gs.print(gd.text.getHTMLValue());

ouput :-
*** Script: <p> </p>
<p><span style="font-size: 18pt;"><strong>How can I find the MAC address of my<span class="Apple-tab-
span"> </span> Ethernet or wireless interface in Mac OS X?</strong></span><span class="Apple-tab-span">
</span></p>
Etc etc
<p> </p>

The getJournalEntry() method in ServiceNow is used to retrieve the journal entries associated with a specific
record. Journal fields are commonly used in ServiceNow to store comments or updates in a structured format,
allowing users to maintain a history of changes or notes.
How getJournalEntry() Works
 Purpose: It fetches entries from a journal field (like work_notes or comments) for a specific
GlideRecord object.
 Return Value: The method returns the journal entry as a string, allowing you to display or manipulate it
as needed.

XMLDocument2 API
The XMLDocument2 API in ServiceNow is used for manipulating XML data. This API provides various
methods to work with XML content, allowing developers to parse, modify, and extract information from XML
documents effectively.
Key Features of XMLDocument2
1. Parsing XML: You can load XML content into an XMLDocument2 object, making it easy to traverse
and manipulate the data.
2. Navigating XML Structure: The API provides methods to navigate through nodes in the XML
document using XPath expressions, which makes it easier to locate specific data.
3. Modifying XML: You can add, update, or remove nodes and attributes in the XML structure.
4. Serializing XML: Once changes are made, the XML can be serialized back into a string for storage or
transmission.
Common Methods
 loadXML(): Loads XML content into the XMLDocument2 object.
 getNode(): Retrieves a specific node from the XML document based on an XPath expression.
 getNodes(): Retrieves a collection of nodes that match a given XPath expression.
 addNode(): Adds a new node to the XML document.
 setAttribute(): Sets an attribute on a specified node.
 toString(): Converts the XML document back into a string format
 parseXML() :- The parseXML() method takes an XML string and converts it into an XMLDocument2
object for manipulation.
 EG;-
 var xmlString = '<root><item>Hello World</item></root>';
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML(xmlString);

// Accessing a node
var itemNode = xmlDoc.getNode('/root/item');
gs.print(itemNode.getValue()); // Output: Hello World
 createElement() :- The createElement() method creates a new XML element.
 var xmlDoc = new XMLDocument2();
 var root = xmlDoc.createElement('root'); // Creating the root element
 xmlDoc.appendChild(root); // Adding the root to the document

 var item = xmlDoc.createElement('item'); // Creating an item element
 root.appendChild(item); // Appending item to root

 gs.print(xmlDoc.toString()); // Output: <root><item/></root>

createElementWithValue () :- The createElementWithValue() method creates a new XML element and sets its
value in one call.
EG:-
var xmlDoc = new XMLDocument2();
var root = xmlDoc.createElement('root');
xmlDoc.appendChild(root);

var item = xmlDoc.createElementWithValue('item', 'Hello World'); // Creating and setting value


root.appendChild(item); // Appending item to root

gs.print(xmlDoc.toString()); // Output: <root><item>Hello World</item></root>


In ServiceNow, documented, undocumented (out of box) APIs exist that can significantly enhance the
functionality of your applications. Here’s a brief guide on how to discover and utilize these APIs:
If you find somewhere
v.someScript().someFunction(); // search for someScript in the script include table
1. Finding APIs
 Script Includes: Many ServiceNow APIs are defined in Script Includes. You can navigate to System
Definition > Script Includes and search for specific scripts. By examining the script, you can find
undocumented api’s available and understand their usage.
 Documentation: For documented APIs, refer to the official ServiceNow documentation. The API
Reference section provides detailed information about various APIs, including usage examples.
2. Helper Functions
 Inside Script Includes: Helper functions are often included within the same Script Include as the main
API functions. Look for methods that are prefixed with an underscore (_) or are private functions that
assist the main public methods. These can provide additional utility or simplify complex processes.

1. GlideModal
The GlideModal API is used to create and manage modal dialogs in ServiceNow. This API helps display
messages or forms to users without navigating away from the current page. Developers can configure modals
with custom content, buttons, and events to interact with user inputs effectively.
Key Features:
 Create modals with HTML content or forms.
 Configure buttons to perform specific actions.
 Handle user interactions via event listeners.
More Information: ServiceNow GlideModal API Documentation

2. Workflow
The Workflow API allows developers to automate business processes through workflows. Workflows consist
of activities that are linked together to create a business process flow. The API provides methods for creating,
modifying, and executing workflows programmatically.
Key Features:
 Create and manage workflows dynamically.
 Access and manipulate workflow instances.
 Execute activities within a workflow.
More Information: ServiceNow Workflow API Documentation

3. GlideSysAttachment
https://developer.servicenow.com/dev.do#!/reference/api/xanadu/server/no-namespace/
c_GlideSysAttachmentScopedAPI
What is GlideScriptableInputStream in ServiceNow?
GlideScriptableInputStream is a ServiceNow API that allows you to handle binary file data (like attachments)
in server-side scripts, particularly in Script Includes, Business Rules, or Scripted REST APIs.

📌 Key Features
✅ Used for handling large files efficiently in scripts.
✅ Streams binary data instead of loading everything into memory at once.
✅ Used in conjunction with GlideSysAttachment to read attachments.

The GlideSysAttachment API is used to manage file attachments in ServiceNow. This API allows developers
to add, delete, and retrieve attachments from records programmatically, enhancing data management and user
interactions.
Key Features:
 Add and remove attachments from records.
 Retrieve file metadata and content.
 Support for various file types.
Key Methods
1. copy(source, target)
o Description: Copies an attachment from one record to another.
o Parameters:
 source: The GlideRecord object of the source attachment (typically from the
sys_attachment table).
 target: The GlideRecord object of the target record where the attachment should be
copied.
2. getAttachments(record)
o Description: Retrieves the attachments for a specified record.
o Parameters:
 record: The GlideRecord object of the record from which you want to fetch attachments.
o Returns: A GlideRecord object containing the attachments.
3. deleteAttachment(attachment)
o Description: Deletes a specified attachment.
o Parameters:
 attachment: The GlideRecord object of the attachment to be deleted (from the
sys_attachment table).
4. write(file, tableName, sysId)
o Description: Writes a new attachment to the specified record.
o Parameters:
 file: The file object (usually obtained from a script or uploaded through the UI).
 tableName: The name of the table to which the attachment should be added.
 sysId: The sys_id of the record to which the attachment should be linked.
5. getContentStream(attachment)
o Description: Retrieves the content stream of an attachment.
o Parameters:
 attachment: The GlideRecord object of the attachment whose content stream is to be
retrieved.
o Returns: An InputStream object representing the content of the attachment.
6. getFileName(attachment)
o Description: Retrieves the file name of the specified attachment.
o Parameters:
 attachment: The GlideRecord object of the attachment.
o Returns: The name of the file as a string.
7. getSize(attachment)
o Description: Retrieves the size of the specified attachment.
o Parameters:
 attachment: The GlideRecord object of the attachment.
o Returns: The size of the attachment in bytes.

More Information: ServiceNow GlideSysAttachment API Documentation

4. RESTMessageV2
The RESTMessageV2 API facilitates RESTful communication in ServiceNow. This API allows developers to
create and send HTTP requests to external systems and services, supporting various methods like GET, POST,
PUT, and DELETE.
Key Features:
 Construct REST requests with headers and parameters.
 Handle authentication for secure communications.
 Process and parse responses easily.
More Information: ServiceNow RESTMessageV2 API Documentation

5. RESTResponseV2
The RESTResponseV2 API is used to handle responses from REST requests sent using the RESTMessageV2
API. This API allows developers to retrieve the status code, headers, and body of the response for further
processing.
Key Features:
 Access response data, including status and body.
 Parse response content for easy data handling.
 Support for error handling and logging.
More Information: ServiceNow RESTResponseV2 API Documentation

6. SOAPMessageV2
The SOAPMessageV2 API allows developers to work with SOAP-based web services. This API enables the
creation, sending, and processing of SOAP requests and responses, providing integration with external SOAP
services.
Key Features:
 Construct SOAP messages with headers and body.
 Send SOAP requests and handle responses.
 Support for complex types and operations.
More Information: ServiceNow SOAPMessageV2 API Documentation

7. SOAPResponseV2
The SOAPResponseV2 API is used to manage responses from SOAP requests sent using the SOAPMessageV2
API. This API provides methods to access response details, such as the body and any faults that may have
occurred.
Key Features:
 Retrieve and parse the SOAP response.
 Handle errors and exceptions gracefully.
 Access individual elements in the response.
More Information: ServiceNow SOAPResponseV2 API Documentation

8. GlideDuration
The GlideDuration API is used to manage duration values in ServiceNow. This API allows developers to
perform operations related to time intervals, such as addition, subtraction, and formatting of duration values.
Key Features:
 Create duration objects from strings or numbers.
 Perform arithmetic operations on durations.
 Convert durations to human-readable formats.
More Information: ServiceNow GlideDuration API Documentation
CREATE YOUR CUSTOM API

var IncidentUtils = Class.create();


IncidentUtils.prototype = {
initialize: function() { },
getIncidentRecords : function(num){
var results = [];
var limit = num || 5;
var gr = new GlideRecord('incident');
gr.orderByDesc('sys_created_on');
gr.setLimit(limit);
gr.query();
while(gr.next()){
results.push(gr.number.getDisplayValue()); }
return results; },
type: 'IncidentUtils' };
running this in background script
var gd = new IncidentUtils().getIncidentRecord(10);
gs.print(gd);

8. GlideEmailOutbound (Sending Emails)


Used to send emails from scripts.
📌 Common Methods
Method Description

email.setSubject('Subject') Sets email subject

email.setBody('Message Body') Sets email body

email.addAddress('to', '[email protected]') Adds recipient

email.send() Sends the email


Summary Table: Server-Side APIs & Their Use Cases
API Purpose

GlideRecord Query, update, delete records

GlideSystem (gs) Logging, messages, user properties

GlideAggregate Aggregation queries (COUNT, SUM)

GlideDateTime Date and time manipulation

GlideRecordSecure Secure record queries (respects ACLs)

GlideSession Session management

GlideUser User details (roles, IDs)

GlideEmailOutbound Sending emails

GlideSystemEvent Triggering events

GlideSchedule Working with schedules

Using GlideEmailOutbound (Server-Side Script)


This method allows sending emails dynamically with custom subject, body, and recipients.
📌 Example (Business Rule, Script Include, or UI Action)
var email = new GlideEmailOutbound();
email.setSubject("Important Notification");
email.setBody("Hello, this is a test email from ServiceNow.");
email.addAddress("to", "[email protected]");
email.send();
gs.log("Email sent successfully!");
GlideModel API
🖼 GlideModal API in ServiceNow
The GlideModal API in ServiceNow is used to create and display modal dialog windows in the classic UI (not
applicable for the Service Portal or Next Experience UI). It provides a way to show forms, messages, or custom
UI Pages as pop-ups.

📌 Example Usage
1️⃣ Display a Simple Modal
var gm = new GlideModal("example_modal");
gm.setTitle("Hello, Sneha!");
gm.setBody("This is a test modal in ServiceNow.");
gm.render();
🔹 setTitle() → Sets the title of the modal
🔹 setBody() → Sets the content inside the modal
🔹 render() → Displays the modal on the screen

📌 2️⃣ Open a Form in Modal


You can use GlideModal to open a form dynamically.
var gm = new GlideModal("glide_form_modal");
gm.setTitle("Create a New Incident");
gm.setSize("large"); // "small", "medium", or "large"
gm.setPreference("sys_id", "-1"); // -1 means new record
gm.setPreference("table", "incident"); // Open the Incident table
gm.render();

📌 3️⃣ Open a UI Page in a Modal


You can open a UI Page inside the modal.
var gm = new GlideModal("my_custom_ui_page");
gm.setTitle("Custom UI Page");
gm.setPreference("param1", "value1"); // Send parameters
gm.render();

📌 4️⃣ Closing the Modal


You can close the modal using:
gm.destroy();

🔹 When to Use GlideModal?


✅ Displaying confirmation dialogs
✅ Opening forms dynamically
✅ Showing UI pages inside modals
✅ Providing additional information without navigating away
However, GlideModal is only supported in the classic UI and is not recommended for Service Portal (use
GlideModalForm instead). Would you like an example for Service Portal? 😊

🛠 setPreference() in GlideModal API (ServiceNow)


The setPreference() method in GlideModal is used to pass data (key-value pairs) to a modal window, typically
when opening a form or a UI Page. These preferences act like parameters that the modal can access and use.

📌 Syntax
modal.setPreference("key", "value");
🔹 "key" → Name of the preference (parameter)
🔹 "value" → Value assigned to the preference

📌 Example 1: Passing a sys_id to Open a Record


You can pass the sys_id of a record to open it inside the modal.

var gm = new GlideModal("glide_form_modal");


gm.setTitle("Edit Incident");
gm.setPreference("sys_id", "1234567890abcdef"); // Pass an Incident record
gm.setPreference("table", "incident"); // Open the Incident table
gm.render();
✅ This opens the incident record with the given sys_id in the modal.

📌 Example 2: Sending Parameters to a UI Page


When opening a UI Page in a modal, you can send dynamic data using setPreference().

var gm = new GlideModal("my_custom_ui_page");


gm.setTitle("Custom Data Modal");
gm.setPreference("user_id", gs.getUserID()); // Pass the current user ID
gm.setPreference("message", "Hello, Sneha!"); // Send a message
gm.render();

✅ The UI Page script can access these values using g_request.getParameter("user_id").

📌 Example 3: Using Preferences in a UI Page


If you pass a preference from GlideModal, you can access it in the UI Page script.
Client-side UI Page Script (Inside UI Page)
var userID = g_request.getParameter("user_id");
var message = g_request.getParameter("message");
✅ This helps in dynamically updating UI Pages based on passed parameters.

🔥 When to Use setPreference()?


✔ Passing data when opening a record form
✔ Sending dynamic values to a UI Page
✔ Making modals context-aware (e.g., opening an Incident linked to a caller)

Example:-
function closeTask() {
var confirm = new GlideModal('close_task');
confirm.setTitle('You are about to close a Task');
confirm.setPreference("onPromptComplete", "ok");
confirm.setPreference("onPromptCancel", "cancel");
confirm.render();
}

//Code that runs without 'onclick'


//Ensure call to server-side function with no browser errors
if (typeof window == 'undefined')
updateTask();

function updateTask() {
current.state = 3;
current.update();
}

📌 Breakdown of Code
confirm.setPreference("onPromptComplete", "ok");
confirm.setPreference("onPromptCancel", "cancel");
🔹 "onPromptComplete" → "ok"
✅ This means when the user confirms (clicks OK), the function assigned to "ok" will execute.
🔹 "onPromptCancel" → "cancel"
✅ This means when the user cancels (clicks Cancel), the function assigned to "cancel" will execute.

var confirm = new GlideModal("glide_confirm_standard");


confirm.setTitle("Delete Record?");
confirm.setPreference("onPromptComplete", function() {
// Execute a server-side script, delete a record, etc.
gs.info("Record deleted!");
});
confirm.setPreference("onPromptCancel", function() {
gs.info("Deletion cancelled.");
});
confirm.render();
g_scratchpad
g_scratchpad is a server-to-client communication object available in ServiceNow. It is used to pass data from
a server-side script (e.g., a Script Include or Business Rule) to a client-side script (e.g., Client Script) without
requiring an additional AJAX call.

Key Features of g_scratchpad:


1. Server to Client: Allows the server-side logic to prepare data that can be accessed in the client-side
script.
2. Efficient: Reduces the need for client-server communication by bundling the data during the initial
form load.
3. Read-Only on the Client Side: Data added to g_scratchpad on the server is read-only on the
How g_scratchpad Works
1. Server-Side Preparation:
o A Display Business Rule adds data to the g_scratchpad object during form load.
2. Client-Side Access:
o The data can be accessed in Client Scripts for dynamic form behavior.
Limitations
1. Form Load Only:

 Populated During Form Load:


The g_scratchpad object is populated on the server side (via a Display Business Rule) when the form
is loading. This data is prepared and sent to the client-side script before the form is fully displayed.

 Cannot Be Dynamically Updated:


Once the form has loaded and the g_scratchpad data has been passed to the client, it cannot be updated
again without reloading the form. If you want to update or fetch new data dynamically after the form is
loaded, you would need to use an AJAX call or other client-server communication mechanisms.

o By populating g_scratchpad during the form load process, ServiceNow allows onLoad Client
Scripts to smoothly and efficiently utilize server-side data. This design pattern helps ensure that
the UI can respond to user actions without requiring extra server requests, enhancing the overall
performance and user experience.
2. Read-Only on Client Side:
o Data passed to g_scratchpad cannot be modified on the client side.
Use Case Example
Server-Side (Display Business Rule):
(function executeRule(current, g_scratchpad) {

// Add data to g_scratchpad

if (current.priority == 1) {

g_scratchpad.highPriorityMessage = "This is a high-priority incident!";

} else {

g_scratchpad.highPriorityMessage = "Priority level is normal.";


}

})(current, g_scratchpad);

Client-Side (Client Script):


(function executeClientScript() {
if (g_scratchpad.highPriorityMessage) {
g_form.addInfoMessage(g_scratchpad.highPriorityMessage);
}
})();

Main Usage: g_scratchpad is specifically designed to work with Display Business Rules because they run at
form load time.
Indirect Access: You can indirectly use g_scratchpad within Script Includes that are called by a Display
Business Rule or another server-side script. However, you cannot directly set g_scratchpad in a Script Include
unless it is part of a Display Business Rule.

NOTE:-
besides g_scratchpad, there are a couple of other methods to get data from the server to the client:
1. GlideAjax
 What It Is: GlideAjax is a mechanism used to make asynchronous calls to server-side scripts (like
Script Includes) from client-side scripts.
 Use Case: When you need to fetch or send data based on user interactions after the form has loaded,
allowing you to dynamically update the UI without reloading the page.

2. getReference
 What It Is: The getReference method is used to retrieve a referenced record from a reference field on
the current record.
 Use Case: When you need to fetch details of a referenced record (like a user or a group) when the form
loads or in response to a user action.
Debugging Tools
Server Side
 Script debugger
 Session debuggers
Client Side
 Browser Console
 Javascript Executer
1. Script Debugger
 Description: The Script Debugger is an interactive tool for debugging server-side scripts. It allows you
to step through code, set breakpoints, and inspect variable values at runtime.
 Usage: Available in Studio, it’s particularly useful for debugging Business Rules, Script Includes, and
other server-side scripts.
 Key Features: Step-through debugging, breakpoints, variable inspection, and execution flow control.
2. Field Watcher
 Description: This tool tracks changes to fields on a form, monitoring real-time updates triggered by
client scripts, UI policies, or workflows.
 Usage: Enable it from the form’s UI actions or the browser console.
 Key Features: View and analyze form field changes in real-time, making it easier to track down client-
side issues.
3. JavaScript Log and jslog()
 Description: Use jslog() within client-side scripts to log messages to the browser console.
 Usage: jslog() sends messages to the browser’s console, allowing you to log custom information for
debugging client scripts.
 Example: jslog("This is a test message");
4. Business Rule Debugging (Debug Business Rule)
 Description: Enables you to see logs specifically for Business Rules, showing you the sequence and
outcome of Business Rule executions.
 Usage: Go to System Diagnostics > Debug Business Rule to turn on debug logging for all Business
Rules.
 Key Features: Shows which Business Rules fired, their order, and the data processed.
5. System Logs (and gs.log, gs.info)
 Description: System Logs collect logs from different parts of the instance, including gs.log, gs.info,
gs.warn, and gs.error messages.
 Usage: Use log statements in your server scripts to print variable values and other information to system
logs.
 Key Features: Filter logs by source, date, and type to easily locate relevant log entries.
6. Background Script Execution
 Description: The Background Script module allows you to test and run server-side scripts directly in
the instance without attaching them to specific records or scripts.
 Usage: Found in System Definition > Scripts - Background, it’s useful for quick script testing,
debugging, and data manipulation.
 Key Features: Execute ad hoc scripts and inspect log output immediately.
7. Log Statement Profiler
 Description: Profiles and logs statements from server-side scripts, providing insights into script
performance.
 Usage: Enable by adding GlideRecordProfiling.enable() and GlideRecordProfiling.disable() to your
scripts to profile GlideRecord usage.
 Key Features: Measures performance metrics like execution time, allowing you to optimize database
queries.
8. Transaction Log and Slow Query Log
 Description: The Transaction Log tracks instance requests, including slow queries, while the Slow
Query Log provides detailed reports on query performance.
 Usage: Accessible in System Logs > Transactions, it helps you diagnose performance issues by
reviewing the duration of various database queries and requests.
 Key Features: Identify and optimize slow-performing scripts and database queries.
Each of these tools can be used individually or in combination depending on the type of issue you're
troubleshooting, whether it’s client-side, server-side, or related to database performance. They help ensure your
code is functioning as expected and enhance overall performance in your ServiceNow environment.

Session Debugging
Enabling session debugging in ServiceNow activates logging and monitoring for a particular user session. This
feature provides insights into the requests and operations happening in real time for that session, which can be
instrumental in diagnosing issues specific to a user's experience. Here’s what happens when session debugging
is enabled:
Key Effects and Benefits of Enabling Session Debugging
1. Increased Log Details:
o The system generates detailed logs for every action performed by the specified user. This
includes Business Rules, workflows, client scripts, and other events that are triggered during the
session.
o Logs capture each step in the execution flow, which can help pinpoint errors, slowdowns, or
unexpected behaviors.
2. Performance Monitoring:
o Every action taken during the session, including database queries, is monitored for performance.
This helps in identifying processes that may be taking longer than expected and could be
optimized.
o The profiler tracks execution time and resource usage, which can highlight potential bottlenecks.
3. Troubleshooting Specific User Issues:
o Since session debugging is enabled for a particular user, it allows administrators or developers to
recreate issues reported by that user and monitor the exact interactions and backend processes in
action.
o This is particularly useful when errors occur intermittently or are unique to certain users based
on their roles, permissions, or session states.
4. Enhanced Visibility into Client-Side and Server-Side Scripts:
o Both client and server-side script executions are logged, allowing debugging of scripts that may
be affecting form behavior, field values, or actions triggered by the user.
o Developers can see the sequence in which scripts fire, making it easier to identify if a particular
script or Business Rule is causing issues.
Potential Downsides
 Performance Impact: Enabling session debugging increases the amount of data logged, which may
slightly impact performance. It is generally recommended to use it temporarily and only when needed.
 Privacy Considerations: Since user actions are tracked in detail, session debugging should be enabled
with consent and disabled after troubleshooting to maintain privacy.

Gs.eventQueue():-
The gs.eventQueue() method in ServiceNow is used to trigger an event programmatically. This can be useful
for various purposes, such as sending notifications, updating records, or triggering background scripts in
response to specific conditions or actions.
Syntax
The basic syntax for gs.eventQueue() is:
gs.eventQueue(eventName, targetRecord, userID, additionalParameters);
Parameters
1. eventName (String): The name of the event you want to trigger. This must match an event defined in
the Event Registry in ServiceNow.
2. targetRecord (GlideRecord): The GlideRecord object representing the record that the event is
associated with. This can be null if no specific record is associated.
3. userID (String): The Sys ID of the user for whom the event is triggered. This is often gs.getUserID() to
specify the current user.
4. additionalParameters (String): A string of additional parameters that you want to pass to the event.
This can be formatted as key-value pairs (e.g., key1=value1;key2=value2)

Notification
Outbound Email
Notifications send outbound email to one or more recipients in response to specific activities in ServiceNow.
Notifications can be sent when:
 Records are inserted or updated
 Events are generated
 The Notification activity executes in a workflow
 The Send Email action executes in a flow
Weight
When multiple Notifications are simultaneously triggered for the same record and addressed to the same
recipient(s), the Weight field value determines which notification(s) to send and which to skip. Use
the Weight field to prevent recipients from receiving multiple or conflicting notifications for the same target
table record or event.
 Notifications with a Weight value of zero are always sent.
 If notifications have non-zero Weight values, only the notification with the highest Weight value is sent.
 If multiple notifications have the same non-zero Weight value and that value is the highest, all
notifications with that value are sent.
https://developer.servicenow.com/dev.do#!/learn/learning-plans/xanadu/servicenow_administrator/
app_store_learnv2_automatingapps_xanadu_who_will_receive
https://developer.servicenow.com/dev.do#!/learn/learning-plans/xanadu/servicenow_administrator/
app_store_learnv2_automatingapps_xanadu_what_it_will_contain

DEVELOPER TIP:
 Statement 1: ServiceNow sends notifications to all recipients in the "Who will receive" section, even if those
users are not authorized to view the record.
 Explanation: This statement highlights that ServiceNow does not automatically filter notification
recipients based on their access to the actual data. For instance, if you add users to the "Who will
receive" section, ServiceNow will send notifications to them, regardless of whether they have the
required permissions to view the specific record in the system.
 Developer Tip: To avoid sharing sensitive information with unauthorized users, carefully select
recipients who already have the necessary permissions to view the data in question.
 Statement 2: Adding a user to a notification's "Who will receive" section does not guarantee the user will
receive the notification.
 Explanation: This statement focuses on user-level settings. Each user’s profile in ServiceNow has
specific notification preferences, which can be configured to receive or ignore certain types of
notifications (e.g., email, push, SMS).
 Developer Tip: Even if a user is added as a recipient, they might not receive the notification if they’ve
opted out in their notification preferences.
In summary:
 Statement 1 addresses access control and advises selecting recipients with proper access.
 Statement 2 deals with user notification preferences, explaining that users may have personal settings
that affect whether they receive notifications.
Using Dynamic Content
The Subject, SMS Alternate, and Message HTML fields can use dynamic content.
 To dynamically reference a field value from the record that triggered the Notification, enclose the field
name in ${ }: ${<field_name>}.
 Use dot-walking to reference field values on related records: ${<field name containing related
record>.<field name>}.
 To reference the event parameters parm1 or parm2, use this syntax: ${event.parm1} or ${event.parm2}.
(Only for notifications fired by events.)
Use the Select variables column to easily construct the dynamic syntax for fields from the record associated
with the notification. Click a field in the Select variables tree to insert the field name and dynamic syntax into
the message
Add Links to Messages
Use clickable links in messages to make it easy for users to access records in ServiceNow or to unsubscribe
from notifications. When clicked, links open a record in ServiceNow for editing.
 URI: Link to the current record. The link text is LINK.
 URI_REF: Link to the current record. The link text is the display value for the record.
 <reference_field_name>.URI: Link to a record determined by dot-walking. Link text is Link.
 <reference_field_name>.URI_REF: Link to a record determined by dot-walking. Link text is
the display value for the related record.
 NOTIF_UNSUB: Link to unsubscribe from notifications. Link text is Unsubscribe.
 NOTIF_UNSUB+link_text="<value to insert as link text>": Link to unsubscribe from notifications.
Link text is specified by the notification developer.
 NOTIF_PREFS: Link to the user's Notification preferences. Link text is Notification Preferences.
 NOTIF_PREFS+link_text="<value to insert as link text>": Link to the user's Notification
preferences. Link text is specified by the notification developer.

DEVELOPER TIP: Maximum notification size including attachments is 26 MB. This size includes MIME
encoding which increases attachment size by 37%.

https://docs.servicenow.com/bundle/xanadu-integrate-applications/page/script/server-scripting/concept/
c_CreatingNewTransformMaps.html
https://docs.servicenow.com/bundle/xanadu-now-intelligence/page/use/dashboards/concept/create-and-edit-
dashboards.html
https://docs.servicenow.com/bundle/vancouver-now-intelligence/page/use/reporting/concept/
c_GenerateReports.html
https://docs.servicenow.com/bundle/vancouver-now-intelligence/page/use/reporting/task/add-additional-group-
by-stack-by.html
Transform Map
a Transformation Map is used in the Import Set process to transform data from an import set table to a target
table. When you import data into ServiceNow from an external source (like a CSV file, Excel, or a database),
the data is first stored in an Import Set Table. To move this data into the desired ServiceNow table (like the
Incident or Change Request table), you create a Transformation Map.
Key Components of a Transformation Map:
1. Source Table:
o This is the Import Set Table where the raw data is stored after being imported.
2. Target Table:
o This is the destination table in ServiceNow where you want the data to be mapped. It could be a
core table like incident, cmdb_ci, or a custom table.
3. Field Mapping:
o Mapping Assist: This tool helps you drag and drop fields from the import set table to the target
table. It simplifies field mapping and ensures that data is correctly transferred.
o Manual Mapping: You can also manually define how each field from the import set table maps
to a field in the target table.
4. Transformation Scripts:
o You can add onBefore, onAfter, onStart, and onComplete scripts for advanced data
processing.
 onBefore: Runs before the transformation process starts for each record.
 onAfter: Runs after a record has been transformed.
 onStart: Runs before the entire transformation starts.
 onComplete: Runs after the entire transformation is completed.
 onChoice Event
 onForeignInsert
onChoice
Triggered when a field in the import set references a choice list field in the target table.
This event allows you to define custom behavior when a choice value is encountered that
does not already exist in the target table's choice list.
Use Case:
Adding missing choice values to the target table's choice list dynamically.
Parameters:
transform: The transform script object.
choiceField: The name of the choice field in the target table.
choiceValue: The new choice value being processed.
 Example: Adding a Custom Choice
Let's say you want to dynamically add a choice to the Priority field of the incident table:
Script Example
Navigate to the Dictionary Entry of the Priority field on the incident table.
Add the following onChoiceCreate script:
function onChoiceCreate(field, currentTable, currentRecord) {
if (field == 'priority' && currentTable == 'incident') {
// Add a new choice dynamically
var newChoice = g_scratchpad.createChoiceObject();
newChoice.label = 'Super Critical'; // Label of the new choice
newChoice.value = '6'; // Value of the new choice
newChoice.sequence = 600; // Sequence for the choice position
g_scratchpad.addChoice(newChoice);
}
}
The g_scratchpad object in your example is not the same as the g_scratchpad used in ServiceNow for data
sharing between server-side and client-side scripts. Instead, this g_scratchpad is a placeholder or a
contextual object created specifically for dynamically adding choices within a script, such as the
onChoiceCreate function.
onForeignInsert Event
 Triggered when a field in the import set is mapped to a reference field in the target table, and the
referenced record does not already exist in the foreign(referenced) table.
 This event allows you to control how missing reference records are handled.
Use Case:
 Automatically create missing reference records in the related table.
Parameters:
 transform: The transform script object.
 foreignTable: The name of the referenced table.
 foreignFieldName: The name of the reference field in the target table.
 foreignValue: The value of the missing reference.

Example Scenario:
Imagine you're importing data into the incident table, and some records contain a reference to the caller field. If
the referenced caller doesn't exist in the sys_user table, you may want to automatically create a new user in the
sys_user table.
(function transformForeignInsert(source, target, map, log, isUpdate) {
// Check if the foreign table is 'sys_user'
if (map.foreign_table_name == 'sys_user') {
// Create or update the user record in sys_user table
var userGR = new GlideRecord('sys_user');
userGR.initialize();

// Populate fields for the foreign record


userGR.user_name = source.caller_id || 'default_user';
userGR.email = source.email || '[email protected]';
userGR.first_name = source.first_name || 'Default';
userGR.last_name = source.last_name || 'User';

// Insert the record


userGR.insert();

// Log the insertion


log.info('Foreign record inserted into sys_user: ' + userGR.sys_id);
}
})(source, target, map, log, isUpdate);

5. Coalesce Fields:
o Coalescing helps identify whether to update existing records or insert new ones. If one or more
fields are set as coalesce fields:
 If a record with matching coalesce fields is found, it is updated.
 If no matching record is found, a new record is inserted.
How to Create a Transformation Map:
1. Navigate to Import Sets:
o Go to System Import Sets > Administration > Transform Maps.
2. Create a New Transform Map:
o Click on New, enter a Name, select the Source Table, and select the Target Table.
3. Define Field Mappings:
o Use Mapping Assist to map fields or manually map them.
4. Configure Coalesce Fields:
o Set the coalesce field(s) if you want to update existing records.
5. Save and Test:
o Save the transformation map and test it by running the import set transformation.
Use Case Example:
If you are importing a list of incidents from an Excel file:
1. Import the Excel file using the Import Set Loader.
2. The data is loaded into an Import Set Table (e.g., u_import_incidents).
3. Create a Transformation Map to map data from u_import_incidents to the incident table.
4. Set coalesce on the number field (if you want to update incidents based on their incident number).
5. Run the transformation map to migrate data from the import set table to the incident table.
//Note: The field names referenced from an import set are
//prefixed with an "u_", also note that it is necessary to use the java method
// toString() to so that we can use JavaScript functions to
//manipulate the data.
var name= source.u_name.toString();

//Use native JavaScript function split to create an array for each word in the name "splitting" it
//anywhere that there is a space
var split_names =name.split(" ");

//Find the number of of names (i.e., first and last name only, or first middle and last name, etc.)
var num_names = split_names.length;

// If there is only one name then map it to the last name field in the user table
if(num_names ==1){
target.last_name= split_names[0];
}

//if there are two names then map the first one to first name and the last one to last name
if(num_names ==2){
target.first_name= split_names[0];
target.last_name= split_names[1];
}

//if there are more than 3 names then all middle names get combined into one middle name this is done
//by shifting off the first name (array element 0 ) and mapping to first name and popping off the last
// name and returning it to the last name field
if(num_names >=3){
target.first_name= split_names.shift();
target.last_name= split_names.pop();
target.middle_name= split_names.join(" ");
}
Enforce Mandatory Fields
 If a target table field is marked as mandatory (required), this setting forces the import process to check
whether these fields have data.
 If any mandatory field is missing in the import data, the record will not be processed successfully.
Example
Just before importing the records from the spreadsheet into the Employee Special Days application, the
application developer added a mandatory field, Employee email, to the Occasions form. Importing the
spreadsheet data will leave a mandatory field with no value.
There is no column in the source data that can be mapped to the Employee email field. One solution is to
modify the source data so there is a column for every mandatory application field. If there were a lot of
records, modifying the source could be time consuming and tedious. Another solution is to write a script to
set the target field value.
Open the Transform Map and select the Run script configuration option. Write a server-side script to
populate the Employee email field.
In the example, corporate email addresses have the format [email protected]. Using the
value in the staging table Employee column, the script creates the email address for the Employee
email target field.
The source object is automatically instantiated. The source object properties are the fields from the staging
table. The source property values are the values from the source data.
The target object is also automatically instantiated. The target object properties are the fields from the target
table. The target property values are the values from the script and the values from the Field Map.

Copy Empty Fields


  When enabled, this option allows empty fields (null or blank values) from the import set table to
overwrite existing values in the target table.
 If the import data contains a blank value for a particular field, and this option is checked, the
corresponding field in the target table will be set to blank (or null).
Create New Record on Empty Coalesce Fields
When enabled, this option allows ServiceNow to create a new record in the target table if the specified
coalesce fields are empty or null during the transformation.
Import a Date Field
Fields containing dates often cause errors on import due to a mismatch in format between the date format in the
data source and the date format ServiceNow expects.
1. Transform Script Column (Field-Specific Script)
 Location: This script is written directly in the "Script" field for each mapping in the Transform Map.
 Scope: It is applied only to that specific field mapping. For example, if you are mapping
u_requested_for to u_requested_for_email, you can directly write the transformation logic in the script
field of that mapping.
 Execution: The script is executed only when mapping that specific field.
 Use Case: It is typically used when you want to perform simple field-level transformations, like
formatting data or setting a specific value.

2. Run Script Checkbox (Overall Transform Script)


 Location: This is available when you tick the "Run Script" checkbox in the Transform Map form.
 Scope: This allows you to write global transformation logic that applies to the entire Transform Map,
across multiple fields. You can access both source and target objects in this script.
 Execution: This script is executed once for each row of the import data, allowing you to handle more
complex transformation logic that might involve multiple fields or conditional processing.
 Use Case: It is used when you need to perform actions that affect multiple fields or involve complex
conditions that cannot be handled in individual field mapping scripts.

 File Formats acceptable for import set by servicenow : there are 4 file formats (xml, excel, csv, json)
 Data sources :- file, ldap, jdbc
How to Handle Missing Mandatory Fields?
To successfully import the data, you can address the missing mandatory fields in one of the following ways:
1. Set Default Values in Transform Map:
o Use a Transform Map script to set a default value for the missing field:
if (!source.caller_id) {
target.caller_id = 'default_sys_id'; // Replace with a valid sys_id for Caller
}
2. Manually Add Missing Data:
o Update the records in the Import Set Table to provide a value for the missing Caller field before
running the Transform Map.
3. Disable Field Mandatory Validation Temporarily:
o This is not recommended in production but can be done by making the field optional
temporarily.
4. Skip the Record:
o Configure the Transform Map to skip records missing the Caller field:
if (!source.caller_id) {
ignore = true;
}
5. Notify on Errors:
o Use the Import Set Error feature to log or notify when a mandatory field is missing.

RUN Transform
Running a transform map imports data from the staging table into the target table. To run a Transform Map,
click the Transform Related Link in the Table Transform Map record.
In the Specify Import set and Transform map form, verify that the Transform Map to run is in the Selected
maps, run in order slushbucket. Click the Transform button.
The Progress page shows the transform's State and Completion code. A Completion code value of Success does
not mean the records imported correctly. The Completion code indicates whether the transform executed
successfully and is not indicative of the data integrity of the records.
Click the Transform history link and select the timestamp to see if there were any errors with the data. In the
example, there are no errors in the Import Set Row Errors section (tab).

Example case:-
, when you encounter errors during data import due to Business Rules like the "NeedIt When needed field
date Business Rule", it usually happens because certain constraints or validations are in place that prevent
invalid data from being saved. Here's how you can resolve the issue by modifying the Transform Map
configuration without disabling the Business Rule.
Problem Recap
 The Business Rule prevents records with the "When needed" date field set in the past or on the current
day.
 The import data (needitimportdata.csv) does not include the "When needed" date field, causing the
Business Rule to trigger an error due to the missing or invalid value during import.
Solution: Adjust the Transform Map Configuration
Instead of deactivating the Business Rule, you can adjust the Transform Map configuration to bypass running
Business Rules during the import process. Here are the steps:
Step 1: Edit the Transform Map
1. Navigate to System Import Sets > Administration > Transform Maps in the main ServiceNow
browser window.
2. Search for and open the "Import Historic NeedIt Data" Transform Map.
Step 2: Disable "Run Business Rules" Option
1. In the Transform Map form, look for the checkbox labeled "Run business rules".
2. De-select (uncheck) the "Run business rules" option.
o This option, when unchecked, ensures that Business Rules, such as the one validating the
"When needed" date, are not executed during the data transformation process.
3. Click the Update button to save the changes.
Step 3: Load Data into the Staging Table
1. Navigate to System Import Sets > Administration > Data Sources.
2. Open the "needitimportdata.csv (Uploaded)" data source record for editing.
3. Scroll down to the Related Links section and click on Load All Records.
o This action loads the data from the CSV file into the staging table (Import Set Table).
Step 4: Run the Transform Map
1. On the Progress page, in the Next steps... section, click the Run Transform link.
2. On the Specify Import set and Transform map page, make sure that the "Import Historic NeedIt
Data" Transform Map is in the Selected maps, run in order slush bucket.
Explanation:
 Disabling the "Run Business Rules" Option:
o This prevents the validation logic in the "NeedIt When needed field date Business Rule" from
executing during the import. It allows the data to be imported even if the "When needed" field
is empty or contains a date in the past.
 Avoiding Deactivation of the Business Rule:
o Instead of deactivating the Business Rule, which would allow all users to bypass this validation
temporarily, you are only skipping the Business Rule check during the import process. This
maintains the desired behavior in other parts of the application.
This method allows you to successfully import the historical NeedIt data without triggering validation errors
related to the "When needed" field date Business Rule.
Do You Need to Load Data Every Time?
 No, you do not need to load the data every time you want to run the Transform Map if the data is
already in the Import Set Table.
o Scenario 1: Same Data - If you are working with the same data set and want to re-run the
transformation (e.g., to test different mappings or scripts), you can simply run the Transform
Map again.
o Scenario 2: New Data - If you need to import new or updated data, then you must load the
data again into the Import Set Table.

Note: Only bar and horizontal bar reports use stacked data. Other report types allow only grouping.
Additional Group By options can be added to bar or pie charts, and also to list reports as columns. For bar
charts, if you add an additional Group By, ServiceNow will also treat it as a Stack By.
  These additional fields can give more flexibility in breaking down the data, but they are not "filtered"
like the main Group By fields, meaning they don’t impact the filtering logic applied to the report.
 Exporting Reports:
 When you configure an additional Group By and then export the report, only the main Group By will
appear in the export, not the additional Group By.
 This means that even though you can view the additional Group By in the UI while viewing the report,
the exported data will only reflect the data grouped by the primary field.
 Using multiple datasets in a report

You can create reports that use datasets from up to five tables in a single report.

The following report types support multiple datasets: bar, horizontal bar, column, line,
step line, area, spline.

Multiple Group bys are not supported on multiple datasets. When using multiple
datasets, the report legend is always displayed.

We can create any report as data source by clicking on save as data source after clicking on dropdown arrow on
save button.

Restrictions
Bear the following restrictions in mind when creating a report with multiple data sets:
 Up to a maximum of 5 additional datasets can be added to any particular report. Keep in mind that each
additional dataset will require additional processing and querying of the database, so if a particular
report is experiencing performance issues, it could be due to the fact the report has multiple data sets
associated.
 All datasets associated with a parent report must be of the same type (such as bar, donut, or pie) as the
parent report.
 For multiple datasets associated with a time series chart, all additional data sets must have the same
setting in the Per field as the parent report.
 For multiple datasets on a Bar or Horizontal Bar chart, all associated datasets must have the same Group
By value.
 The Show Legends option is always, by default, displayed on a report with multiple datasets, even if the
parent report has this option unselected.

Create a report from an imported Microsoft Excel document


You can import Excel spreadsheets (.xlsx files) of data maintained outside of your instance and create reports
from those files.
You must have the subscription version of Performance Analytics to create reports with imported data

Dashboard
Edit rights to a dashboard do not necessarily give you edit rights to the widgets on that dashboard.
Enter an Order number to indicate the order the dashboard appears on the dashboard
picker. Dashboards with lower numbers are listed first.
Click the magnifier icon to add the dashboard to a Group. Groups organize dashboards in the dashboard picker
list. Grouped dashboards appear at the top of the list. Ungrouped dashboards appear in the list under Other.
Four types of aggregation are available for single-score reports: Count, Average, Sum, and Count Distinct.
Real-time updating is available only for single score widgets that use the Count aggregation.
Role required: Only users with the dashboard_admin or admin role can change a dashboard owner.
Dashboard
a dashboard is an interactive, visual interface that allows users to display various types of data and analytics in
a drag-and-drop canvas format. These dashboards help in monitoring key metrics and evaluating business
performance on a daily basis.
Here’s a breakdown of key aspects of dashboards in ServiceNow:
Key Features of Dashboards in ServiceNow:
1. Drag-and-Drop Interface:
o ServiceNow provides a drag-and-drop canvas where users can place and organize different
widgets and reports for easy viewing.
o The user can customize the layout and appearance of the dashboard to suit their needs.
2. Widgets:
o Widgets are individual components that display different types of data. You can add widgets to a
dashboard to display real-time information and reports. Some common types of widgets include:
 Performance Analytics widgets: For tracking metrics and KPIs.
 CMDB (Configuration Management Database) widgets: To visualize data related to
the configuration items (CIs) in the CMDB.
 Reports: To show pre-built or custom reports.
 Interactive Filters: Allow users to interact with data by filtering the content displayed
on the dashboard (e.g., by date, location, or category).
3. Role-Based Access:
o Dashboards can be shared with specific users or roles. For example, an Admin or Dashboard
Admin role can create and manage dashboards.
o Once created, a dashboard can be shared with other users or roles who need to access the data,
providing different levels of visibility and interactivity.
4. Dashboard Creation Permissions:
o Users with the appropriate roles (such as Admin or Dashboard Admin) can create and
configure dashboards.
o Admins have the highest level of control, enabling them to create dashboards, manage widgets,
and define access for other users.
5. Real-Time Data and Analytics:
o Dashboards often display real-time data and allow for continuous monitoring of business
activities, key performance indicators (KPIs), and service metrics.
o Performance Analytics can be embedded within a dashboard to track service levels, incidents,
requests, and other key metrics.
6. Sharing and Collaboration:
o Dashboards can be shared with specific users or groups, allowing teams to collaborate and make
data-driven decisions.
o Access to dashboards can be restricted based on user roles, ensuring that sensitive information is
only visible to authorized users.
Example Use Cases:
 Incident Management: A dashboard showing incident resolution times, number of open incidents, and
performance analytics on incident management metrics.
 Change Management: A dashboard with widgets displaying the status of changes, upcoming changes,
and performance indicators for change success rates.
 CMDB Health: A dashboard that monitors the health and status of configuration items (CIs) in the
CMDB, with a focus on ensuring accurate data and configuration integrity.
How to Create a Dashboard in ServiceNow:
1. Create Dashboard: From the Dashboard module, you can create a new dashboard and provide a name
and description.
2. Add Widgets: Use the drag-and-drop feature to add widgets to the dashboard. You can configure each
widget to display specific data, like reports, charts, or performance indicators.
3. Set Permissions: Use the Access Control Rules or share options to control who can view or modify the
dashboard.
4. Save and Share: Once the dashboard is set up, it can be saved and shared with the appropriate roles or
users.

Copy a responsive dashboard


When you duplicate a responsive dashboard, its widget layout is preserved. However, sharing permissions
aren’t preserved. Changes you make to the duplicated dashboard don’t affect the original dashboard.

Reports don’t answer important business questions therefore we use performance analytics.
Configure ServiceNow so that all users see the same dashboard when they log in. Role required: admin. The
dashboard that you configure should be available to all users.
When you select Replace colors with patterns with charts and graphs, you can see how the visualization's
solid colors become differently patterned for more accessible viewing.
Data table enabled
When you select Enable data table for charts and graphs, data tables replace the charts on Performance
Analytics widgets. On reports, a plus + icon appears.
Dashboard Statistics
The Dashboard Stats list enables you to view how often each of your Core UI dashboards is run and how long
it takes to run them.
To view dashboard statistics, navigate to All > dashboard_stats.list. The admin or dashboard_admin role is
required. By default, the Dashboard Statistics list displays all dashboards that have been viewed. There is one
entry in this table for each dashboard on the instance.
 The Dashboard Stats list enables you to view how often each of your Core UI dashboards is run and
how long it takes to run them.
 The Dashboard executions list shows how long it takes for your Core UI dashboards to load and the ID
of the user who launched it.
 The Dashboard execution statistics list how long it takes for your Core UI dashboards to load. The list
includes one entry for the most recent launch of each dashboard per user.

When you publish a report in ServiceNow, it makes the report accessible to a broader audience and allows
users to view it without navigating through the Reports module. Here's what happens:
1. Generates a Public URL:
 Publishing a report creates a unique public URL or direct link for the report.
 Anyone with this URL can view the report without needing to open the Reports section in ServiceNow.
 This is useful for sharing the report with users who might not have direct access to the Reports module
but need to view the data.
2. Visibility:
 The published report is generally set to be viewable by all users who have access to the instance, but
the visibility can be controlled based on user roles and permissions.
 You can specify whether it should be visible to everyone or only to users with certain roles.

No, a user who does not have access to the ServiceNow instance cannot view a published report by default.
Here’s why:
1. ServiceNow Access Requirement:
 Published reports in ServiceNow are still hosted within the ServiceNow instance.
 Even though the report is made publicly accessible within the instance, the user still needs to have
access to the instance itself to view the report.
 Users must be able to log in to the ServiceNow instance to access the published report.
2. Role-Based Access Control:
 The visibility of the published report is often controlled by roles and permissions within ServiceNow.
 By default, only users who can log into the instance and have the necessary permissions can view the
report, even if it is published.
What is a Database View in ServiceNow?
A Database View in ServiceNow is a virtual table that combines data from multiple tables using SQL JOINs.
It is not a physical table but rather a way to represent related data from different tables as a single logical table.
This is particularly useful when you need to create reports that require data from multiple related tables.
Why Use Database Views?
 To join data from multiple tables without manually exporting and merging data.
 To create complex reports that need to pull in related information from different tables.
 To simplify querying across multiple tables by presenting them as a single, unified view.
Examples of Using Database Views:
 You might have a table for Incidents and another table for Change Requests. If you want to create a
report that shows incidents along with related change request information, you can create a Database
View to join these tables based on a common field, like the task_id.

Example Scenario:
Let’s say you want to create a report that shows:
 Incident Number from the incident table.
 SLA Definition and SLA Start Time from the task_sla table.
1. Create a Database View joining the incident table and task_sla table on incident.sys_id = task_sla.task.
2. Use this Database View as the data source in your report.
3. Create a List Report or Bar Chart based on the fields you want to display.
ACL RULES:-
https://www.servicenow.com/docs/bundle/xanadu-platform-security/page/administer/contextual-
security/concept/exploring-access-control-list.html
ACL evaluation process
An ACL rule only grants a user access to an object if the user meets all conditions required by the matching
ACL rule.
 The condition must evaluate to true.
 The script must evaluate to true or return an answer variable with the value of true.
 The user must have one of the roles in the required roles list. If the list is empty, this condition evaluates
to true.
 [Record ACL rules only] The matching table-level and field-level ACL rules must both evaluate to true.

WILDCARD RULES:-
Wildcard ACL Rules in ServiceNow
Wildcard ACL rules are general access control rules that apply broadly across all tables or fields without
targeting a specific table or field. They act as catch-all rules to ensure there are baseline permissions in place
when no specific ACL rule is defined.
Types of Wildcard ACL Rules
1. Table-level Wildcard ACL (*):
o These rules apply to all tables in the system.
o Example: *.read, *.write, *.create, *.delete.
o If a user tries to perform a read operation on a table without a specific ACL rule, the wildcard
rule (*.read) will be evaluated.
Example:
o *.read: Allows read access to all tables unless a specific table rule overrides it.
o *.create: Controls create access across all tables unless explicitly defined otherwise.
2. Field-level Wildcard ACL (*.*):
o These rules apply to all fields in all tables.
o Example: *.*.read, *.*.write, *.*.create.
o When accessing a field without a specific field-level ACL rule, the field-level wildcard rule (*.*)
is used.
Example:
o *.*.read: Grants read access to all fields across all tables unless a specific field rule exists.
o *.*.create: Allows users to create entries and personalize choices for all fields if no specific rule
overrides it.
Purpose of Wildcard ACL Rules
 Fallback Mechanism: They provide a default access control mechanism, acting as a safety net when
no specific ACL rules are defined for a table or field.
 Simplified Permissions: Useful when you want to set broad permissions across the system without
configuring individual rules for every table and field.
Example Scenario
 If you want to allow read access to all tables but only restrict write access on specific tables like
incident, you might have:
o A table-level wildcard ACL: *.read (allows read access to all tables)
o A specific table ACL: incident.write (restricts write access on the incident table)
In this case:
 The *.read wildcard rule provides read access across all tables.
 The incident.write rule specifically controls write access on the incident table.

1. Security Manager Default Behavior (glide.sm.default_mode) Property


 Property Overview:
o glide.sm.default_mode is a system property in ServiceNow that controls access behavior when
a user attempts to access objects (tables or fields) that only match wildcard ACL rules (* for
tables and *.* for fields).
 Deny Access Setting:
o If glide.sm.default_mode is set to Deny access, only administrators will be able to access
objects matching the wildcard ACL rules.
o For non-administrative users, this setting means they cannot access any object that only
matches a wildcard ACL rule. They would need specific ACL rules defined for access.
 Example:
o If there is a wildcard table ACL rule (*.read) but no specific read rule for the incident table,
and glide.sm.default_mode is set to Deny access:
 A non-admin user will not have access to read incident records, even though there is a
wildcard ACL (*.read) because the property is set to Deny access.
 An admin user, however, will still have access due to their elevated permissions.
2. Wildcard Field ACL Rule (*.*) for Create Operation
 Field ACL Overview:
o In ServiceNow, when a user performs a create operation (adding a new record), the system
evaluates whether the user has write permissions on each field.
o The wildcard field ACL rule (*.*) for the create operation reuses the same conditions as the
write operation.
 What This Means:
o If there is a wildcard ACL rule for writing fields (*.*.write), its conditions will also apply when a
user tries to create a new record.
o Unless you define a separate, specific create ACL rule (e.g., incident.number.create), the system
will reuse the write ACL rule (*.*.write) for creating new records.
 Example:
o You have a wildcard field ACL rule for writing: *.*.write, with a condition like "User role is
itil_user".
o When a user tries to create a new record and set a value for a field, ServiceNow will check if the
user satisfies the conditions of *.*.write.
o If there is no specific create rule defined (field_name.create), the write conditions are applied
for the create operation.
o This means that if the user does not meet the conditions of *.*.write, they cannot set that field
value during record creation.
Key Takeaways
 glide.sm.default_mode:
o Controls whether non-admin users can access objects using only wildcard ACL rules. Setting it
to Deny access restricts access to only administrators when no specific ACL rules are defined.
 Create vs. Write ACL Rules:
o The create operation inherits the conditions of the write operation's wildcard field ACL rule
(*.*.write) unless a specific field-level create ACL rule is explicitly defined.
Who Can Create Custom ACL Rules in ServiceNow?
 Admin (admin): Has full access to create and manage ACL rules.
 Security Admin (security_admin): Can create and manage ACL rules after elevating their role in the
session.
Example Scenario:
Let’s consider a user trying to read a record from the incident table:
 Step 1: Match the Table Name:
o The system first checks if there is a specific ACL rule like incident.read. If it exists, the rule is
evaluated.
 Step 2: Match the Parent Table Name:
o If there is no specific ACL rule for incident, the system checks for its parent table (task.read)
since incident inherits from task.
 Step 3: Match Any Table (*):
o If neither incident.read nor task.read ACL rules exist or match, the system checks the wildcard
table ACL rule (*.read).
 Outcome:
o If the user fails to meet the conditions of all these checks, they cannot access any data in the
incident table.
o If the user passes any of these table ACL rules, then the system moves on to evaluate field-level
ACL rules to see which specific fields the user can access.
Access is denied only if all the rules fails.
Field ACL rules
After a user passes a table ACL rule, field ACL rules are processed in the following order:
1. Match the table and field name. For example, incident.number.
2. Match the parent table and field name. For example, task.number.
3. Match any table (*) and field name. For example, *.number.
4. Match the table and any field (*). For example, incident.*.
5. Match the parent table and any field (*). For example, task.*.
6. Match any table (*) and any field (*). For example, *.*.
A user must pass the table ACL rule to be granted access to the table's fields. For example, the user must first
pass the table ACL rule for the incident table to access the Number field in the incident table.
The first successful field ACL evaluation stops ACL rule processing at the field level. When a user passes a
field ACL rule, the system stops searching for other matching field ACL rules. For example, if a user passes the
field ACL rule for incident.number, the system stops searching for other ACL rules that secure
the Number field in the incident table.
Client-callable script include ACL rules
Script include ACL rules specify the client-callable script include to be secured. For a list of available script
includes, navigate to System Definition > Script Includes. You can personalize the list to show the Client
callable column.
The base system does not include any ACL rules for client-callable script includes.
Client-callable script include ACL rules honor the STAR (*) rule if they cannot find a more specific ACL for
those resources.
UI page ACL rules
UI page ACL rules specify the UI page to be secured. For a list of available UI pages, navigate to System
UI > UI Pages. When defining an ACL rule for a UI page, use the fully scoped page name. For
example, x_myapp_mypage.
Note: You can use the STAR (*) character in the Name field on ui_page type ACLs to match any UI pages.
UI page ACL rules honor the STAR (*) rule if they cannot find a more specific ACL for those resources. For
example, if you have a UI page named mysecretpage but do not define an ACL for this UI page, the STAR (*)
rule for the UI page processor is used for access check.
ACL rules can secure the following UI page operation:

Operation Description

read Allows users to display the UI page.

ACL control of function fields


When evaluating access to a function field, in addition to checking access to the function field itself, the system
also checks access to the function's contributing fields. Contributing fields are those used as the arguments in a
given function definition
In Xanadu and later, the system also requires access to all contributing fields in order to allow access to the
function field. If one or more of the contributing field ACLs refuse access, the function field also refuses
access..
ACLsResult
 total, base: read and report_view for role salary_admin, with no conditions or scripts
 bonus: report_view for role salary_admin , with no conditions or scripts
 bonus: read for role bonus_admin, with no conditions or scripts
A user with the salary_admin role is refused read and report_view access to total, because bonus refuses read
access to their role.
What Are Function Fields in ServiceNow?
Function Fields in ServiceNow are special types of fields that do not store data directly in the database.
Instead, they dynamically compute values based on existing data or logic. These fields are useful when you
want to display a calculated or derived value without actually storing it in the database table.
Characteristics of Function Fields:
1. Dynamically Computed: The value is calculated on-the-fly using a script or a formula when the field
is accessed.
2. Read-Only: Since the values are derived and not stored, users cannot directly modify them.
3. Not Stored in the Database: Function fields are virtual fields, meaning they do not occupy space in
the database table.

How to Create Function Fields in ServiceNow


Method 1: Using a Client Script
A simple way to create a function field is by using a client script or UI policy that calculates the value and
displays it in a read-only field on a form.
1. Create a New Field in the Table:
o Navigate to System Definition > Tables.
o Select the desired table and create a new field with the desired label (e.g., Full Name).
o Set the type to String and mark it as read-only.
2. Create a Client Script:
o Go to System UI > Client Scripts.
o Click New and set the following properties:
 Name: Descriptive name (e.g., Calculate Full Name).
 Table: The table where the field exists (e.g., User).
 Type: Form, onLoad.
o Script:
function onLoad() {
var firstName = g_form.getValue('first_name');
var lastName = g_form.getValue('last_name');
var fullName = firstName + ' ' + lastName;
g_form.setValue('full_name', fullName);
}
o This script calculates the full name based on first_name and last_name fields and displays it in
the full_name field.
Configure ACL Rules
Access Control Rules have two decision types, and these types will behave differently depending on conditions.
1. Allow Access: Allows access to a resource if all conditions are met.
2. Deny Access: Denies access to a resource unless all conditions are met.
What are Query ACLs?
Query ACLs are special rules that decide who can query (search) data in a table and how they can search it.
They help to protect sensitive data by limiting the type of queries a user can perform.
Why are Query ACLs important?
 Imagine you have a table with sensitive information like employee salaries.
 You don't want users to be able to search through the entire table and see the salaries of everyone.
 Query ACLs help control what kind of searches users can do to prevent them from snooping around
for data they shouldn't see.
Types of Query ACLs:
There are two main types:
1. query_match ACLs:
 These allow specific searches using safe operators like:
o Equals (=): Find records that match a specific value.
o Is Empty: Check if a value is empty.
 Example: You can search for your profile by your ID (e.g., Employee ID = 123).
 Why use this? It is safe because you are looking for one specific record.
 What happens if you don't pass the rule?
o You can't perform these specific searches.
2. query_range ACLs:
 These allow broad searches using operators like:
o Greater than (>=)
o Starts with
o Contains
 Example: You might want to search for all employees with salaries between $50,000 and $100,000.
 Why is this risky? It allows you to see a range of data and could reveal information you shouldn't
have access to.
 What happens if you don't pass the rule?
o You can't do range-based searches or sort data by certain fields.
Default Behavior:
 If there are no specific Query ACLs, the system uses a default rule (*.*), meaning it checks if you have
read access to the table.
 If Query ACLs are defined, they take priority and are stricter than the default rule.
When to Use Query ACLs:
 Use Query ACLs when:
o The table has sensitive data.
o You want to restrict access to certain queries, so users can't easily guess or extract hidden
information.
Example Scenarios:
1. Payroll Example:
o You can view your own salary but shouldn't be allowed to search for all salaries within a certain
range because it's private information.
o A query_range ACL can prevent such broad searches.
2. HR Profiles Example:
o You can view your Social Security Number (SSN) but shouldn't be allowed to search for SSNs
of all employees.
o A query_match ACL can limit you to only look up your own record.
Summary:
 query_match: Allows safe, specific searches (e.g., searching for one exact record).
 query_range: Restricts risky, broad searches (e.g., searching a range of values).
 Why use them? To protect sensitive data and prevent unauthorized users from seeing information they
shouldn't access.
Explanation of Audit User Roles in Contextual Security Manager:
What is Role Auditing?
Role auditing is a feature in the Contextual Security Manager that helps track changes to user roles. It logs
updates when roles are added, removed, or modified for users and groups. This is essential for security
compliance, allowing administrators to monitor who has access to what, and detect any unauthorized changes
in user roles.
Why is it Important?
 Compliance and Security: In many organizations, role assignments are crucial because they control
access to sensitive data. Auditing ensures you can track who made changes, when, and what changes
were made.
 Change Tracking: It helps maintain a history of role changes, making it easier to troubleshoot access
issues.
Contextual Security Manager & Role Management V2:
When you activate Role Management V2 plugin:
 It prevents duplicate entries in the user roles table (sys_user_has_role). In earlier versions, inherited
roles could cause multiple identical entries, cluttering the role table.
 You need to enable role auditing by setting a system property:
o Property: glide.role_management.v2.audit_roles
o Purpose: This property allows the system to log changes in an Audit Roles table.

Audit Roles Table:


The Audit Role List is a feature in ServiceNow that helps track changes made to user roles. It is part of the
Role Management V2 plugin, which is designed to manage roles and their inheritance more effectively.
What is an Audit Role List?
 It is a record-keeping system that logs any changes made to user roles, such as adding, removing, or
modifying a user's role.
 The purpose is to maintain a history of role changes for security and compliance reasons.
 It allows administrators to review who made changes to user roles and when these changes were made.
Why is it useful?
 Security Compliance: Ensures that all changes to roles are tracked, making it easier to audit who has
access to sensitive data.
 Troubleshooting: Helps in identifying issues if there are unexpected changes in access permissions.
 Accountability: Provides a clear record of role modifications, showing which admin made the changes.
 It stores audit records related to changes in user roles.
 It captures details like:
o User ID: Who made the change.
o Timestamp: When the change was made.
o Action: What type of change (added, removed).
o Old Role vs. New Role: The previous role setup compared to the current.
Example:
1. Scenario:
o Suppose you assign the admin role to a user.
o The action is logged in the Audit Roles table.
o If the admin role is removed later, this action is also logged.
2. Audit Entry:
o User: John Doe
o Action: Role Added
o Role: admin
o Timestamp: 2024-11-10 10:00 AM
Benefits:
 Security: Identifies any unauthorized role changes.
 Audit Trail: Provides a clear history of role modifications.
 Compliance: Helps meet regulatory requirements for user access control.
How to Enable Role Auditing:
1. Activate Role Management V2 Plugin (com.glide.role_management.inh_count).
2. Set the system property:
o Go to: System Properties → Security.
o Set glide.role_management.v2.audit_roles to true.
This setup ensures all role changes are captured, providing a robust audit mechanism to maintain a secure
environment.
EXAMPLE:-
To enable users with only the snc_external role to access the list view of a table, you must create a series of
ACLs.
Before you begin
Role required: security_admin
Procedure
1. Elevate to a privileged role.
2. Create an ACL rule with the following settings:
o Type: ui_page
o Operation: read
o Name: {table_name}_list
o Required role: snc_external
3. On the default read ACL for the table, add snc_external in the Required role list.
Create the ACL if it does not already exist.
4. Use these settings to create another ACL:
o Type: ui_page
o Operation: read
o Name: {table_name}
o Required role: snc_external
5. Use these settings to create another ACL to give the user write access to a field in the table:
o Type: record
o Operation: create
o Name: {table_name} {column_name}
o Required role: snc_external
Repeat this step for every field that you want to give the user write access to. Use an asterisk * instead of the
column name to provide access to all fields at once.
Why Create Separate ACLs for GlideAjax Calls?
1. Bypassing Standard UI Restrictions:
o When a user interacts with the UI, ACL rules automatically protect access to certain tables and
fields. However, GlideAjax calls are server-side API calls made from client scripts.
o Without explicit ACL checks on GlideAjax, users might be able to access data they shouldn't
see, even if they cannot access it directly via the UI. This is because GlideAjax executes on the
server and might bypass typical client-side access controls.
2. Security Vulnerability:
o If you do not apply ACL checks to GlideAjax requests, it can become a security vulnerability.
For example, if an ESS (Employee Self-Service) user makes a GlideAjax call to fetch data from
a restricted table (like cmn_location), they might retrieve information they are not authorized to
see.
3. System Property for ACL Enforcement:
o ServiceNow provides a system property (glide.ajax.enforce_acl) that can be set to ensure ACL
validation on all GlideAjax API calls.
o When this property is enabled, any request made through GlideAjax will be subject to the same
ACL rules as any other request. If the logged-in user does not have permission to read a table
via ACL, the GlideAjax call will also fail.
plaintext
Copy code
Property: glide.ajax.enforce_acl
Value: true
Example Scenario:
 Let’s say you have a table called "cmn_location".
 If an ESS user tries to access it via a UI form, they cannot see the data because the ACL denies them
read access.
 However, if you have a client script making a GlideAjax call that fetches data from "cmn_location"
without ACL checks, the request might return data unless ACL validation is enforced explicitly.
 By enabling the property glide.ajax.enforce_acl = true, you ensure that GlideAjax requests are also
denied if the user lacks proper permissions.
Direct ACL Creation vs. System Property
 You can directly create an ACL on a table or field to restrict access. This works well for UI-based
requests.
 However, for server-side API calls (like those made by GlideAjax), explicit ACL checks are necessary
because these calls do not automatically respect the same restrictions as UI requests unless the property
is set.
In short:
 Direct ACL: Restricts access to specific users or roles for UI and standard server operations.
 System Property for GlideAjax ACL: Ensures API calls made via GlideAjax also enforce these
restrictions, preventing unintended access through server-side scripts.
This approach maintains consistency in access control across different request types (UI and API).
Das
WORKFLOW
WORKFLOW ACTIVITY
Approval Rules
the Approval Engine is a mechanism used to manage approval processes for tasks across different
applications, such as Service Catalog Requests and Change Management. The goal is to provide flexibility in
how approvals are handled, as companies may have different processes for managing approvals.
Key Points to Understand:
1. Approval Rules (Recommended Option):
o This is the simplest and most commonly used approval engine.
o How it works: Approval rules are evaluated to determine which users need to approve a task.
The system checks for matching conditions, and when a match is found, it assigns the approval
tasks to the appropriate users.
o Setup: You can set up approval rules by navigating to System Policy > Approvals in
ServiceNow.
o Advantages: It is easy to configure and maintain, and it is widely used for many task tables like
incidents, change requests, or service catalog items.
2. Process Guides (Deprecated):
o How it works: Process Guides define a sequence of approval steps. You can control the flow of
approvals and rejections manually in these steps.
o Why it's Deprecated: ServiceNow recommends moving away from Process Guides because
they are harder to maintain and provide less flexibility than newer approaches.
o Usage: Even though it’s deprecated, this option is still available but should be avoided.
3. Turn off Engines:
o How it works: This option disables both the approval engines for the specific Task table, which
means no approval rules or process guides will be used.
o When to Use: You might want to turn off the approval engines if a workflow (created using
Flow Designer or other methods) is responsible for managing the approval process instead.
o Note: Not turning off the approval engines when using workflows could lead to performance
issues or unexpected behavior, as two different methods of approval might try to execute
simultaneously.
Why Approval Engines Matter:
 Flexibility: Different types of approval engines allow you to tailor approval processes according to your
company's needs.
 Performance: Disabling unnecessary approval engines (when using workflows) ensures better system
performance by avoiding conflicting processes.
 Flow Designer: The newer, recommended method of handling approvals in ServiceNow is using the
Flow Designer’s Ask for Approval action. It is easier to maintain, offers better reporting, and integrates
well with other ServiceNow features.
you can define approval rules for specific tables in ServiceNow. Approval rules are typically associated with
task tables (tables that extend the Task table, like Incident, Change Request, Service Catalog requests, etc.).
These rules define the conditions under which a record needs approval and the users or groups responsible for
providing that approval.
When do Approval Rules get Executed?
Approval rules are executed based on the conditions defined within them. Here’s how it works:
1. Record Creation/Update: When a record (e.g., a change request or service catalog item) is created or
updated, ServiceNow evaluates any approval rules that are associated with the table.
2. Conditions Matching: The system checks the approval conditions (such as specific field values, user
roles, etc.). If a condition in the rule matches, the approval is triggered for that record.
3. Approval Requests: The system creates approval requests for the users or groups defined in the
approval rule. These users can approve or reject the request, and the record’s state is updated
accordingly (e.g., moving from "Pending" to "Approved" or "Rejected").
Why Can't We Use the Approval Activity in a Workflow if the Approval Engine is On?
While you can set up approval rules for a task table (via the Approval Engine), ServiceNow recommends
turning off the approval engines if you are using Workflows (or Flow Designer) to manage the approval
process. Here's why:
1. Redundancy: When you use approval rules (via the Approval Engine) and a workflow (using the
Approval activity), both are trying to manage the same approval process. This can create conflicting
behavior, where the system tries to send approvals in two different ways, causing confusion and errors.
2. Performance Issues: Having two approval mechanisms active (the Approval Engine rules and the
Approval activity in workflows) can lead to unnecessary processing and performance degradation, as
both systems would be checking for approvals at the same time.
3. System Conflicts: The Approval Engine is a built-in system designed to handle approvals in a simple
and automated way. If you also use the Approval activity in a workflow, these two mechanisms might
conflict, leading to inconsistent behavior or errors.
When to Use Approval Rules vs. Approval Activity in a Workflow
 Approval Rules (via the Approval Engine): Use when you want to automate approval processes
without manually managing each approval step. This is easier to maintain and ideal for simpler approval
processes that are straightforward and based on matching conditions (like user roles or task states).
 Approval Activity in Workflow: Use when you need more customized or complex approval
workflows. This is ideal for situations where you need to create multiple steps in an approval process or
require conditional logic (like different approval flows depending on the type of request or department).
When Using Workflows:
 If you're using workflows to manage approvals (via the Approval activity), turn off the Approval
Engine for that table.
 This ensures that the workflow can take full control over the approval process without interference from
the approval rules.
the Approval - User activity is part of workflows, and it helps automate the approval process by waiting for
users to approve or reject tasks. Each approval activity can have multiple conditions to determine the next step
in the workflow, based on the result of the approval process (whether it is Approved or Rejected).
Key Components of the Approval Activity Conditions
1. Result Value: The result value is the outcome set by the activity once it has completed, i.e., when an
approval or rejection is received. The result value is typically defined within the activity's script. This
value can then be used in the condition field to transition to different steps of the workflow based on
the approval outcome.
For example:
o If the result value is 'approved', the workflow might transition to the next task or complete.
o If the result value is 'rejected', the workflow might trigger a different action, like notifying the
requester or updating the task with a rejection status.
2. Adding Custom Conditions: In the New Workflow Condition dialog box, you can define a
JavaScript condition that checks certain criteria before transitioning the workflow. The condition can
use certain variables for more complex logic.
Procedure to Add Conditions:
To add a condition to the Approval - User activity, follow these steps:
1. Right-click on the Activity: Right-click the Approval - User activity in your workflow and select Add
Condition from the context menu.
2. Fill in the New Workflow Condition:
o Name: Provide a label for the condition, which will be displayed in the workflow.
o Activity: The system auto-populates this field with the name of the activity you're creating the
condition for (e.g., "Approval - User").
o Short Description: Write a brief description of this condition to make it easier for others to
understand.
o Condition: Here, you'll write the JavaScript condition. You can use:
 current: Refers to the record the workflow is running on.
 activity.result: The result of the approval activity (e.g., 'approved' or 'rejected').
 activity: This refers to the specific Workflow Executing Activity record. It’s useful
when performing more advanced condition checks.
 activity.vars: Refers to the variables associated with the activity.
o Skip During Generate: If this is selected, the workflow won't automatically generate tasks or
approvals during this transition.
3. Submit: Once all the fields are completed, click Submit to save the condition.
Example of Conditions:
For example, if you want the workflow to continue when an approval is rejected, you might set the condition
like this:
activity.result == 'rejected'
Similarly, for an approved condition:
activity.result == 'approved'
Condition Workflow Example:
 Condition: activity.result == 'rejected'
 Description: The activity transitions if the approval is rejected.
 Condition: activity.result == 'approved'
 Description: The activity transitions if the approval is granted.
Activity Result Values:
The activity.result variable is essential in this process. It controls how the workflow transitions based on the
approval or rejection outcome. This result is generally set in the activity script, so when an approver approves
or rejects a task, the activity result value is updated, and the workflow moves through the appropriate condition.
For example, the script inside the Approval - User activity might look like this:
javascript
Copy code
// Script within the Approval activity
if (approvalStatus == 'approved') {
activity.result = 'approved'; // Sets result value to 'approved'
} else if (approvalStatus == 'rejected') {
activity.result = 'rejected'; // Sets result value to 'rejected'
}
If a match is found:
 ServiceNow impersonates the user when taking action in response to the email.
 Scripts have access to the user's information through the GlideSystem methods such
as gs.getUserName().
If no match is found:
 If automatic User creation is enabled, Users are created automatically and then impersonated.
 If automatic User creation is disabled, the user Guest is impersonated.
ACTION
https://docs.servicenow.com/bundle/xanadu-platform-administration/page/administer/notification/concept/
c_InboundEmailActions.html
NOTE: By default, inbound emails of the Forward type always generate new incidents regardless of the
presence of a watermark. If this behavior does not match desired business logic, change the recognized reply
and forward prefixes to treat forwards like replies.
The mailto protocol is a URI (Uniform Resource Identifier) scheme that allows users to create a new email
message using their default email client directly from a web page or application. When a user clicks on a link
formatted with mailto, it opens their email application with predefined fields such as the recipient's email
address, subject line, and body content.
Exploring Service Catalog
You can use Service Catalog to customize portals where your customers can request catalog items such as
service and product offerings. You can also standardize request fulfillment to ensure the accuracy and
availability of the items in the catalogs.

Service catalog let us request items(goods) or services like (password reset, report an IT issue).users can create
an it report issue through simplified forms known as record producers because these forms create records in the
servicenow table.

When a user orders a catalog item in ServiceNow, the following process typically occurs:
1. Item Selection: The user browses the Service Catalog and selects an item (e.g., software, hardware).
2. Order Form: The user fills out a request form with required details (e.g., quantity, configurations).
3. Request Submission: The form submission creates a Request (REQ), and within it, Requested Items
(RITM) are generated.
4. Approval Workflow: The request may trigger approval workflows if required.
5. Fulfillment: Once approved, tasks (Catalog Tasks - SCTASK) are created for fulfillment teams.
6. Completion: After all tasks are completed, the RITM is marked as fulfilled, and the user is notified.

Sequential order guide


To configure a sequence in Playbooks to fulfill items in Order Guides, follow these steps, ensuring you have
the necessary plugin installed and the appropriate roles. Here's a step-by-step procedure:
Prerequisites:
 The Order Guide Sequential Fulfillment plugin
(com.glideapp.servicecatalog.order_guide_sequencing) must be installed. You can check and activate it
by navigating to System Plugin in ServiceNow and searching for the plugin.
 Required roles: admin or a combination of catalog_admin and playbook.admin.
Steps to Configure Sequence in Playbooks for Order Guides:
1. Navigate to Order Guides:
o Go to All > Service Catalog > Catalog Definition > Order Guides.
o Select the Order Guide you want to configure for sequential fulfillment.
2. Generate Sequence:
o On the Order Guide form, click the Generate Sequence button located at the top-right of the
form.
o A pop-up dialog will appear prompting you to enter a name for the sequencing process. Enter a
name (for example, "Order Guide Fulfillment Sequence").
o Click Generate.
3. Playbook Configuration:
o After clicking Generate, the Playbooks page will open in a new tab. The items in the order
guide are now automatically placed into Lane 1 based on their sequence in the rule base.
4. Modify Lane Name (Optional):
o To change the name of Lane 1, click on Lane Actions > Configure Lane. Modify the name
according to your needs.
5. Configure Activities:
o In Lane 1, you will see activity cards for each item in the order guide. These cards represent the
steps needed to fulfill the items.
o Select an activity card for the item you want to configure.
o Configure the activity's properties (e.g., timing, conditions) to define when the item should be
fulfilled. This configuration will ensure that the item is only fulfilled after all prior items in the
sequence have been completed.
6. Configure Dependencies:
o Set up any dependencies between the items. If an item depends on another to be completed
before it, ensure that these dependencies are correctly set so that items don’t move to the in-
progress state prematurely.
7. Review and Finalize:
o Once the sequence and activity configurations are done, review the Playbook to ensure that
items are fulfilled in the correct order.
o The requested items will remain in the pending state until their fulfillment condition is met.

The plugin com.glideapp.servicecatalog.order_guide_sequencing in ServiceNow provides functionality to


configure and manage sequential fulfillment for items in an Order Guide. When this plugin is activated, it
allows you to control the sequence in which items within an order guide are fulfilled, making it easier to handle
complex workflows where certain items need to be completed before others.
Key Features of the Plugin:
1. Sequential Fulfillment:
o It enables you to define a specific sequence in which the items in an Order Guide are fulfilled.
o Items do not move to the in-progress state immediately when the order guide fulfillment starts.
Instead, they remain in the pending state until the sequence reaches the point where they should
be processed.
2. Integration with Playbooks:
o The plugin integrates with Playbooks to track and manage the sequential fulfillment process.
o When you generate a sequence for an order guide, the system automatically creates a Playbook,
where the items from the order guide are placed in lanes according to the sequence defined in the
rule base.
3. Flexibility in Item Fulfillment:
o Items within the order guide will only be fulfilled when the required conditions are met. For
example, one item in the sequence might need to be fulfilled before another dependent item is
processed.
4. Order Guide Management:
o It supports the management of Order Guide items by ensuring that the fulfillment of each item
happens in a controlled, step-by-step manner.
o You can set rules that govern the order of fulfillment, so you can decide which items should be
processed first and which ones should be delayed until others are completed.
5. Conditions and Dependencies:
o You can configure dependencies between the items, ensuring that tasks or records are only
created when the earlier steps in the order guide sequence are completed.
Benefits:
 Better Control: Ensures a controlled and sequential workflow for fulfilling order guide items.
 Improved Efficiency: Reduces the chances of items being fulfilled prematurely, improving the overall
workflow.
 Easier Management: Streamlines complex service requests where multiple tasks need to be handled in
a specific order.
When to Use:
 Complex Order Guides: This plugin is ideal for order guides that involve multiple tasks with
dependencies, such as service catalog requests that require sequential approval, provisioning, or other
dependent actions.
 Custom Workflow Needs: When there’s a need to dictate the precise order in which catalog items
should be fulfilled (e.g., handling software installation steps in a precise order).

In the rule base of the order guide , all the catalog items of that order guide are mentioned.

Item Variable Assignments in the Order Guide, it could be due to the following reasons:
1. Permission or Role Issue:
 Ensure you have the necessary admin role or the required catalog roles (such as catalog_admin) to
access and configure these settings. The Item Variable Assignment feature is generally available to
users with the admin role.
2. Order Guide Configuration:
 Item Variable Assignments only appear when you're working with Order Guide rules and specific
variables are configured. If your order guide doesn’t have any variables, you might not see the section
for Item Variable Assignments.
3. Service Catalog Configuration:
 Verify that you're working in the Service Catalog and not a different application. The Item Variable
Assignments are specific to the catalog configuration.
4. Check Related Lists:
 If you're viewing the Order Guide form, scroll down to check the Related Lists. Make sure you're in
the Rule related list, as that's where the Item Variable Assignments will appear.
5. Ensure You Have a Valid Rule:
 You need to have a valid Order Guide Rule set up to see the Item Variable Assignments section.
Without rules, the assignments won't appear.
Steps to Check or Access Item Variable Assignments:
1. Navigate to Order Guides:
o Go to All > Service Catalog > Catalog Definition > Order Guides.
2. Open the Desired Order Guide:
o Choose the Order Guide you are working on.
3. Open the Rule of the Order Guide:
o If you haven't set up a rule yet, create one under the Order Guide Rules tab.
4. Look for Related Lists:
o Scroll down to the Item Variable Assignments related list under the Order Guide Rule section
(not under the main Order Guide form).
5. Check Configuration of the Order Guide Variables:
o Make sure you have defined variables for your order guide. Without variables, the Item
Variable Assignments section will not show up.
Additional Checks:
 Plugin Installed: Ensure that your instance has all the necessary plugins installed for the service catalog
to work as expected. The Service Catalog functionality should be enabled by default, but sometimes
certain features or plugins need to be activated.
Steps to Enable and Use Cascading Variables:
1. Create a Variable Set:
o Navigate to Service Catalog > Catalog Definition > Variable Sets.
o Click New to create a variable set.
o In the Variable Set form, create the variables that you want to use in the Order Guide and the
catalog items.
o Save the variable set.
2. Add the Variable Set to Order Guide and Catalog Items:
o Open the Order Guide form.
o In the Variables tab, select the Variable Set you created and add it to the order guide.
o Similarly, open the Catalog Item form and add the same variable set to each catalog item.
o This ensures that the variables are available for both the order guide and the catalog items.
3. Enable Cascading:
o When configuring the Order Guide, make sure the Cascade variables checkbox is selected.
o This enables the cascading feature so that the values entered by the user in the order guide will
automatically propagate to the corresponding variables in the catalog items.
4. Ensure Matching Variable Names:
o Ensure that the variables in the Order Guide and Catalog Items have matching names. This is
necessary for the cascading to work. For example, if you create a variable named
delivery_location in the order guide, there must also be a delivery_location variable in each
catalog item.
5. Use a Catalog Client Script to Hide Cascaded Variables:
o If you want to hide the duplicated variables on the Choose Options screen, you can use a
catalog client script. For example, an onLoad script can hide the variables once they have been
cascaded to the catalog items.
 You can run an order guide automatically from within a workflow or a server script,
passing parameters to that order guide to define variable values.

 Automatically generate a set of ordered items as part of a wider process, without


needing to manually submit a service catalog request and reenter existing
information.

 For example, you can run an order guide to fulfill HR onboarding requests, passing
parameters such as the new employee's position and department. The order guide
then generates a set of requested items such as laptop and email account, based
on those parameters.

 Single Row Variable Set:

 When ordering a laptop, a form collects one-time input for "User's Name",
"Department", and "Reason for Request".

 Multi-row Variable Set:

 When ordering multiple software items, a form allows the user to add multiple
rows, each specifying "Software Name", "Version", and "License Count" for
different software.

Define a content item


A content item is a service catalog item that provides information instead of goods or services.
About this task
Content items can reference knowledge articles, static blocks of text, or external web-based content.
To define content items:
Procedure
1. Navigate to All > Service Catalog > Catalog Definition > Content Items.
2. Click New.
3. Fill in the form to define the item

Clone a request

You can clone a request for up to 10 users on the notification list.

Before you begin


Your admin must enable cloning of requests before you can clone a request. For more information,
see Clone requests.

Role required: admin

About this task


4. When you clone a request that contains a multi-row variable set, the information that is specified in the
multi-row variable set is available in all cloned requests. All UI policies and client scripts on the multi-
row variable set are also cloned.

CATALOG BUILDER

The Catalog Builder in ServiceNow is a feature designed to simplify the process of creating and managing
service catalog items. It allows users, even those with limited technical expertise, to build and configure catalog
items using predefined templates. This tool helps streamline the development of service offerings by providing
a guided experience, reducing the need for extensive input from administrators and developers.

Key features of Catalog Builder include:

1. Template-Based Creation: Users start by selecting a template, which ensures consistency and
standardization across catalog items. Templates may include settings for catalog categories, fulfillment
methods, and user criteria.

2. Guided Configuration: The process involves filling out details like item names, descriptions, questions
(variables for user input), and setting access controls. This step-by-step guide simplifies item creation,
making it more accessible for non-technical users.

3. Fulfillment Integration: Users can link catalog items with predefined workflows or ServiceNow's
Flow Designer for request fulfillment. This ensures a smooth end-to-end process for handling requests.

4. User-Friendly Interface: The interface is designed to be intuitive, allowing business users to contribute
directly to the service catalog without deep technical knowledge. However, more complex
customizations still require input from developers or admins.

Overall, the Catalog Builder enhances self-service capabilities within ServiceNow, allowing organizations to
more efficiently manage their service catalogs and improve user experience by making service offerings more
accessible and standardized
The Service Catalog acts as a self-service marketplace, allowing employees to browse through a list of
available items and make requests based on their needs. The Catalog Builder simplifies the process of adding
these items by providing a user-friendly, guided interface that helps standardize the creation of items without
deep technical expertise.

For more complex configurations like approval workflows, dynamic pricing, or custom scripts, administrators
often need to go beyond the Catalog Builder and use the full capabilities of the Now Platform to enhance and
fine-tune these catalog items.

In summary:

 Catalog Builder = Tool to create catalog items easily.

 Catalog Items = Orderable products or services (software, hardware, access requests).

 Service Catalog = A collection of these items, forming a user-facing service portal.

 If you don't use the Catalog Builder in ServiceNow, you can still create catalog items using the
traditional method via the Now Platform interface.
 Go to the ServiceNow application menu and type "Maintain Items" in the search bar. This will take
you to the list of existing catalog items.

Limitations of Catalog Builder in ServiceNow

1. Restricted Entity Creation:


o The Catalog Builder does not support creating or editing some entities directly. For instance:
 Catalog Items, meta tags, execution plans, price settings, and variable settings are
not editable within the Catalog Builder interface. These can only be modified in the
broader Now Platform by administrators.
 Tool tips and advanced reference qualifiers cannot be configured directly in the
Catalog Builder if they involve dynamic or complex setups.
2. Question and Variable Limitations:
o While basic question types like single-line text, multi-line text, dropdown, checkbox, radio
buttons, and date/time inputs are supported, more complex scenarios (e.g., two-level container
questions or two-column sets) are not editable.

In ServiceNow, a conversational catalog item is designed to be easily interacted with via the Virtual Agent
(VA). It is structured in a way that allows users to engage in a natural, chat-based dialogue to place an order
or request, using simplified and supported input types (like dropdowns, checkboxes, or text inputs).

A non-conversational catalog item, on the other hand, may have complex forms, unsupported input fields,
or advanced configurations that are not optimized for chat-based interactions, making it difficult for users to
order through the Virtual Agent.

Specify related items and articles for a catalog item


Specify related items and articles for a catalog item to provide alternatives and additional information. These
items and articles are displayed in the catalog item page in Service Portal and Now Mobile.
Before you begin
Role required: admin, catalog_admin, or catalog_editor
About this task
You cannot specify related items and articles for an order guide.
You cannot specify these types of items as related items for a catalog item.
 Wizard Launcher
 Content Item
 Standard Change Template
 Any item in Admin Home catalog
Procedure
1. Navigate to All > Service Catalog > Catalog Definitions > Maintain Items.
2. Select the required catalog item.
3. To specify a related article, perform these steps.
a. In the Related Articles related list, click Edit.
b. On the Edit Members form, move the required articles from the Collection column to
the Related Articles List column.
c. Click the up or down icon to arrange articles in the required order and click Save.
4. To specify a related catalog item, perform these steps.
a. In the Related Catalog Items related list, click Edit.
b. On the Edit Members form, move the required items from the Collection column to the Related
Catalog Items List column.
c. Click the up or down icon to arrange items in the required order and click Save.

In ServiceNow, Ordered Item Links provide users with additional information about a catalog item after it's
ordered. To set this up:
1. Go to All > Service Catalog > Catalog Definition > Ordered Item Links.
2. Click New, provide a name, link text, and the URL.
3. Choose a target option (new window/tab or within catalog).
4. Submit the link.
5. To link it to a catalog item, go to Service Catalog > Catalog Definition > Maintain Items, select the
item, and set the Ordered Item Link field to the new link.
This helps users access relevant details like terms or conditions directly from the order summary page.
Create a Service Catalog client script
Use catalog client scripts to control the behavior of the catalog items when presented to your users. Catalog
client scripts can be applied to a catalog item or a variable set. These scripts run on the browser instead of the
server, allowing you to better control the information that the user submits.
The priority order for g_form APIs is:
1. Mandatory (highest)
2. ReadOnly/Display
If a variable is set to mandatory and doesn’t have a value, readonly or hide doesn't work on that variable. If a
variable is hidden or readonly, and then set to mandatory, the variable field becomes visible or editable.
This priority order is also applicable for variable sets and containers. If a variable set or container has a
mandatory variable without any value, then the container or variable set can’t be hidden.
Catalog Conversational Coverage

ServiceNow® Catalog Conversational Coverage provides a dashboard to view a high-level overview of the
conversational and non-conversational catalog items.
You can view this information in the Conversational catalog overview dashboard. The dashboard displays a
graphical representation of various reports, such as the number of conversational and non-conversational
catalog items, reasons that make the items non-conversational, and popular request channels. It also shows a list
of the catalog items, their conversational status, and other details.
Drilling down the catalog items, you can view the details, for example, whether they’re conversational or non-
conversational and why the items are non-conversational. Explore the potential suggestions for non-
conversational items that might help you make the items conversational.
If you have any of the following roles, you can view the dashboard:
 Catalog administrator [catalog_admin]
 Catalog manager [catalog_manager]
 Catalog editor [catalog_editor]
To access and view the dashboard, you must install and activate the Catalog Conversational Experience plugin
(sn_catalog_con_cov). You can find the plugin in the ServiceNow® Store.

Create a category
Administrators and catalog administrators can create or edit a category.
Configure dynamic categories
Dynamic categories let you organize and display commonly requested items and knowledge articles. Dynamic
categories appear on the right side of the service catalog homepage by default.
Before you begin
Role required: admin
About this task
Use dynamic categories to provide users with an access option that automatically adjusts to changing request
trends.
To configure dynamic catalog categories:
Procedure
1. Navigate to All > Service Catalog > Catalog Definition > Maintain Dynamic Categories.
2. Select New or open an existing dynamic category.
3. Fill in the fields on the Dynamic category form, as appropriate.
The Dynamic category form contains many of the same fields as the Category form. Additional fields are:
Name of form

Field Description

Type The kind of items to display. Can be Requested items or KB Articles

Search how For catalog items only, the period during which to search for the most common requests. For
long? enter 7 00:00:00 to display the most commonly requested items in the previous seven days.

Number of
The number of items to display in the dynamic category.
Entries

In ServiceNow, a Catalog Portal Page is a customized homepage for a specific service catalog. It provides a
tailored interface and user experience for different user groups, showcasing catalog items relevant to them. For
example, one portal page might be designed for employees to request software, while another might be tailored
for IT staff to handle hardware requests.
Each catalog has a default portal page created when the catalog is set up, but you can create additional portal
pages to offer different views or features depending on user needs.
Scriptable service catalog variables

In ServiceNow, scriptable service catalog variables are used to interact with and retrieve values from
catalog variables in a server-side script. They allow you to access user inputs or predefined values in a
catalog item programmatically during the processing of a request item (sc_req_item).
For example, if you have a catalog item with a variable set or individual variables defined, you can access
these variables using the GlideRecord API. This is often done in server-side business rules, script includes,
or other background scripts that need to process user inputs from the service catalog request.
Example Usage
In your script:
var now_GR = new GlideRecord('sc_req_item');
if (now_GR.get('request_item_sys_id')) {
var variables = now_GR.variables.getElements();
for (var i = 0; i < variables.length; i++) {
var question = variables[i].getQuestion();
gs.log(question.getLabel() + ": " + question.getValue());
}
}
Here, the now_GR.variables object is used to fetch the variables associated with the catalog request item,
iterating through each to retrieve its label and value.
This scripting capability is essential for handling dynamic user inputs, executing conditional logic based on
form values, and automating backend workflows triggered by catalog requests
To create a Multi-row Variable Set (MRVS) in ServiceNow, follow these steps:
Steps to Create a Multi-row Variable Set
1. Navigate to the Variable Set Creation Page:
o Go to Service Catalog > Catalog Variables > Variable Sets.
o Click on New to create a new variable set.
2. Configure the Multi-row Variable Set:
o Set Type to Multi-row variable set.
o Provide a Name, Description, and Order.
o Save the variable set.
3. Add Variables to the Multi-row Variable Set:
o Once the MRVS is created, you will see a related list for Variables.
o Click New to add variables to this MRVS.
o For each variable, provide:
 Name: The internal name for the variable.
 Question: The label users will see.
 Type: The type of input (e.g., text, choice, checkbox).
 Order: The order in which the variables appear in each row.
o Save each variable.
4. Associate MRVS with a Catalog Item:
o Go to Service Catalog > Maintain Items.
o Open the catalog item where you want to include the MRVS.
o In the Variables tab, click New and search for the created MRVS.
o Add it to the catalog item.
Example Use Case
Suppose you want to create a form where users can request multiple software installations in a single
service request. You might create an MRVS with variables like:
 Software Name (text)
 Version (choice list)
 Number of Licenses (integer)
When the user opens this catalog item, they can add multiple rows, each specifying a different software to
install.

Variables
Example Use Cases:
 Single Line Text: Entering a username or short comment.
 Multiple Line Text: Providing a detailed incident description.
 Reference: Selecting a user from the sys_user table.
 Choice (Drop-down): Selecting a department from predefined options.
 Date/Time: Choosing a preferred date for an appointment.
 Boolean
 checkbox
Variable Attributes:
ServiceNow variables can have additional attributes that control their behavior:
 Read-only: Makes the field non-editable.
 Mandatory: Requires the user to fill out the field.
 Default Value: Specifies a pre-filled value for the variable.
 Visible/Hidden: Controls whether the field is visible on the form.

Create a catalog request from another flow


It explains how to create a request in the Service Catalog from another flow, such as when
you are dealing with an incident (like an issue reported by a user).
Why would you do this?
Imagine you are handling a user issue (an incident), and you need to request something
from the Service Catalog, like ordering a new software license. This process allows you to
create and track this new request directly from the incident, linking both together.
Procedure:
1. Navigate to Parent Table:
 Go to the table where the parent record exists (e.g., an incident table).
2. Create Request:
 Click on the Additional actions menu and select Create Request.
3. Catalog Selection:
 The Catalog Home page opens, showing all active catalogs you can access.
 If there is only one active catalog, it opens automatically with the list of available
categories.
4. Select Catalog Item:
 Choose the required catalog item, order guide, or record producer.
 Proceed with checkout of the selected item.
5. Request Creation:
 A new request is created and associated with the parent record:
 For a catalog item or order guide: The request appears under the Requests tab.
 For a record producer: The task appears under the Problems tab of the parent record.
6. Automatic Population of Caller:
 If the request is created from an incident, the caller of the incident is automatically set as
the Requested For user in the request.
 If a two-step checkout is enabled, the fulfiller can change the Requested For user.
7. Delegated Request Experience:
 The caller is populated in the Requested For field when using delegated request
experience (allowing someone else to request on behalf of another user).
8. Limitations:
 You cannot add items to a wish list or save a record producer request during this flow.
You can create a catalog request directly from the incident form in ServiceNow. This feature allows you
to:
1. Link the catalog request with the incident, so both can be tracked together.
2. Simplify the process by avoiding the need to leave the incident form and manually create a separate
request.
Example:
 If a user reports an issue through an incident (e.g., "My laptop is broken"), you can:
1. Open the incident form.
2. Click on the Additional actions menu and select Create Request.
3. This takes you to the Service Catalog, where you can select a relevant item (e.g., "Request a new
laptop").
4. The new catalog request will be automatically linked to the original incident.
1. Request (REQ)
 A Request (also known as REQ) is a high-level container that represents a user's service request.
 It is created when a user places an order from the Service Catalog.
 The request can contain one or more Requested Items (RITMs).
2. Requested Item (RITM)
 A Requested Item (RITM) represents a single catalog item within the request.
 Each RITM is a separate, individual line item within a Request.
 The RITM tracks the status of that specific item, such as "In Progress," "Waiting for Approval," or
"Closed Complete."
3. Task (TASK)
 A Task is a specific action or step that needs to be performed to fulfill a Requested Item (RITM).
 Tasks are created under an RITM when certain actions are required to complete the RITM.
 There can be multiple tasks for a single RITM.
Execution Plans in ServiceNow
Execution Plans are used in ServiceNow to define a sequence of tasks or actions that need to be completed
to fulfill a Requested Item (RITM). They provide a way to automate the task creation process based on
certain conditions or criteria specified for catalog items.
Key Points:
1. Purpose:
 Execution Plans are primarily used for complex catalog items that require multiple steps (tasks)
to be completed in a specific order.
 They help ensure that tasks are automatically generated when a Requested Item (RITM) is
created.
2. Attachment:
 Execution Plans are attached to Catalog Items, not directly to RITMs.
 When a user orders a catalog item that has an associated Execution Plan, the plan is triggered
when the RITM is created.
3. How Execution Plans are Attached:
 You attach an Execution Plan to a Catalog Item via the Catalog Item Configuration.
 This setup allows ServiceNow to know which sequence of tasks should be created when the
catalog item is ordered.
How to Configure an Execution Plan for a Catalog Item:
1. Create an Execution Plan:
 Navigate to Service Catalog > Execution Plans.
 Click New to create a new execution plan.
 Define the Name, Description, and specify the Catalog Item this plan is associated with.
2. Define Execution Plan Tasks:
 Under the execution plan, you can add Execution Plan Tasks.
 Specify details such as Task Order, Assignment Group, Task Type, and any Conditions that
need to be met.
3. Attach Execution Plan to Catalog Item:
 Navigate to Service Catalog > Catalog Items.
 Open the specific Catalog Item you want to attach the execution plan to.
 In the Related Links section, set the Execution Plan field to the execution plan you created.
How Execution Plans Work in Action:
1. When a user orders the catalog item, a Requested Item (RITM) is created.
2. The Execution Plan associated with the catalog item is triggered.
3. Based on the execution plan, tasks are automatically created under the RITM in the defined sequence.
4. These tasks must be completed in the specified order to fulfill the RITM.
Example Scenario:
 Catalog Item: "New Laptop Setup"
 Execution Plan:
 Task 1: Approve Laptop Purchase
 Task 2: Procure Laptop
 Task 3: Install Software
 Task 4: Deliver Laptop to User
When the "New Laptop Setup" catalog item is ordered:
 A Requested Item (RITM) is created.
 The Execution Plan triggers the creation of tasks in the defined order.
 The fulfillment process follows the steps defined in the execution plan.
Difference Between Workflow and Execution Plan in ServiceNow
Both Workflows and Execution Plans are used in ServiceNow to automate processes and streamline the
fulfillment of Requested Items (RITMs). However, they serve different purposes and are used in different
scenarios. Let's explore their differences:

Feature Workflow Execution Plan

A graphical representation of a business


process with a series of activities (e.g., A predefined sequence of tasks created to
Definition approvals, tasks, notifications). fulfill a specific catalog item request.

Best for complex fulfillment processes that Ideal for simple, linear task fulfillment
require approvals, conditions, branching where only task sequence needs to be
Use Case logic, and scripting. defined.

Can be used with any type of record (e.g., Primarily used for Service Catalog items
Scope incidents, changes, catalog items). (RITMs).

Highly flexible, allowing for complex


branching, conditions, and customized Less flexible, primarily focuses on creating
Flexibility actions. sequential tasks for RITMs.

Designed using the Workflow Configured in the Execution Plan module


Design Tool Editor (graphical tool in ServiceNow). through form-based configuration.

Tasks and approvals can be created


Task dynamically based on conditions and Tasks are created in a predefined, linear
Creation branching logic. sequence.

Used for complex approval processes, Used for catalog items that have a
Common multi-step fulfillment processes, and straightforward series of fulfillment tasks
Use customized notifications. without the need for dynamic branching.

Approval Supports complex, multi-level approval Does not support approvals; focused only
Support processes. on task sequence.

Setting up a new employee, which includes Fulfilling a request for a software


dynamic approvals, conditional branching, installation with a fixed sequence of tasks
Example and notifications. like procurement, installation, and testing.

When to Use Workflow:


 Complex Processes: When the fulfillment process involves multiple decision points, approvals, or
conditional paths.
 Custom Actions: When you need to perform custom actions, such as sending notifications, updating
records, or triggering external systems.
 Non-Catalog Items: Workflows can be used for incidents, changes, problems, and other record types
beyond just catalog items.
When to Use Execution Plan:
 Simple Task Sequences: When the fulfillment process involves a simple, sequential list of tasks
without complex decision-making.
 Catalog Items: Primarily used for catalog items in the Service Catalog module, focusing on the creation
of tasks for RITMs.
 Fixed Processes: When you have a standard, repeatable process that does not require branching or
complex logic.
How Task Notifications Work in Execution Plans:
1. Execution Plan Trigger: When a user requests an item from the Service Catalog (e.g., a catalog item
associated with an execution plan), the system creates a Requested Item (RITM) and automatically
triggers the Execution Plan attached to that item.
2. Task Creation: As part of the execution plan, tasks are created in sequence. These tasks are based on
the configuration you set within the execution plan.
3. Task Assigned to Fulfillment Group:
 In the task configuration, if you specify a Fulfillment Group (a group of users responsible for
fulfilling the task), that fulfillment group is associated with the task.
 The Assigned To field of the task is usually set to members of the fulfillment group or a
specific user depending on your configuration.
4. Notification Trigger:
 Once the task is created and assigned to the fulfillment group, ServiceNow will trigger
a notification based on the Notification Rules defined for the task or RITM.
 Notification templates are used to inform the members of the fulfillment group. These
notifications can include details about the task that needs to be fulfilled, such as task
instructions, priority, and any associated details.
5. When the Notification Goes Out:
 The fulfillment group will receive notifications based on the notification rule configuration.
This means members of the group will be informed when the task is assigned to them or when
the task reaches a specific state (e.g., when the task is created, or when it is ready for action).
6. Configuration of Notifications:
 You can define specific notifications for tasks that are triggered when certain events occur. For
example, a notification can be sent:
 When a task is created.
 When a task is assigned to a user.
 When a task is completed.
 When the task is updated or when there are status changes.
Notifications are configured under the Notifications module, where you can set conditions and triggers for
the type of message that should be sent to the assigned group.
To summarize:
 When a catalog item associated with an Execution Plan is requested, the tasks defined in the plan are
created.
 If a Fulfillment Group is set for the task, the task will be assigned to that group.
 Task notifications will be sent to the members of the Fulfillment Group based on the notification rules
set up for tasks. This will alert the group to take action on the task, such as fulfilling the request.
WORKFLOW ACTIVITIES
these are the states for each workflow activity in ServiceNow, which define the current execution state of
a particular activity within the workflow. These states are part of the workflow engine’s internal tracking of
the activity's progress. The states are primarily displayed in the activity card in the Workflow Editor or
within the Workflow context in ServiceNow.
States
The activity state tells the workflow engine what to do with the activity.
Wait for condition activity states

State Description

Executing The workflow engine knows to start the onExecute function of the activity.

Waiting The workflow engine ignores the activity until a specific event to restart the activity is fired.

Finished The activity finished running. See the result value for the outcome of the activity.

Cancelled This activity, or the workflow that contains this activty, was canceled.

Error A JavaScript error occurred. Review the logs for error details.

Wait for WF Event workflow activity


the "Wait for Event" activity is used to pause the workflow until a specific event is triggered. This allows
workflows to stop and wait for an external action or system event to occur before continuing the execution
of subsequent activities.
How the "Wait for Event" Activity Works:
 Purpose: The activity halts the workflow's progress until a specific event is fired. The event is typically
an internal event (like an approval decision, a task completion, or another system action) that signals the
workflow to proceed.
 Behavior: When the workflow reaches the "Wait for Event" activity, it pauses and doesn’t continue
executing any further activities until the event it is waiting for is triggered. Once the event occurs, the
workflow will resume and move to the next step.
Key Concepts:
1. Event: In ServiceNow, events are used to signal certain actions, such as the completion of a task or the
approval of a request. Events are typically fired using the gs.eventQueue() method in scripts or by using
triggers set up within the platform.
2. Waiting State: While the workflow is in this activity, the state of the activity is "Waiting", meaning the
workflow is idle, awaiting the event to be fired.
3. Event Name: When configuring the "Wait for Event" activity, you specify the event name. This event
name is the identifier that the workflow will look for. For example, the event could be something
like task_approved, incident_resolved, or a custom event that is relevant to your business process.
Results
The workflow designer can assign a result value using activity.result from within a script field of the
activity. This activity transitions when the specified event fires.
Input variables
The following variables determine the behavior of the activity.
Note: Condition activities run as the user whose actions match the conditions the workflow was waiting for
and advances the workflow.
Wait For WF Event activity input variables

Field Description

Wait for Event An event name to trigger the workflow.

States
The activity state tells the workflow engine what to do with the activity.

Timer Workflow Activity:


The Timer activity in ServiceNow workflows allows you to set up a pause or delay in the execution of the
workflow for a specified period of time. This is useful when you need to wait for a certain amount of time
before proceeding with the next activity in the workflow.
How It Works:
 Timer Activity pauses the workflow for a set duration, after which the workflow continues executing
the next activity.
 Duration: You can set the duration for the timer in days, hours, minutes, or seconds.
 Use Cases:
 Waiting for a specified time before performing a task (e.g., waiting for a certain number of hours
before escalating an incident).
 Delaying a notification to be sent after a certain period.
 Introducing pauses in a workflow for business logic (like waiting for a manual review to be
completed).
Example Use Case:
Imagine you're handling an incident workflow where the first step is to assign the task to a technician. You
want to wait for a certain period (e.g., 24 hours) before escalating the incident if no action has been taken.
1. Assign Task (Task assigned to technician)
2. Timer (Waits for 24 hours)
3. Escalation (If no updates, escalate the task)
Configuring Timer Activity:
1. Add the Timer activity to your workflow.
2. Define the duration (e.g., 2 hours, 1 day).
3. Specify the next step the workflow should take after the timer expires.

SLA Percentage Timer Workflow Activity:


For workflows running on the Task SLA table, this activity pauses the workflow for an amount of time
equal to a percentage of an SLA. For example, in the Default SLA workflow below, an SLA Percentage
Timer activity at the beginning waits for 50 percent of SLA duration. Between events, two more SLA
Percentage Timer activities wait for 25 percent each of SLA duration. A Join waits for all activities to
complete and then the workflow ends.

The SLA Percentage Timer is a specialized version of the Timer activity that works in conjunction with
Service Level Agreements (SLAs). It helps track the percentage of the SLA elapsed and determines when
certain actions should be taken based on how much time has passed relative to the SLA.
How It Works:
 SLA Percentage Timer checks the percentage of the SLA time that has passed and triggers the next
activity based on the percentage or time.
 It’s commonly used for SLA-based workflows, where certain actions should be triggered depending on
how much of the SLA time has been consumed.
 Condition-Based Actions: The action triggered after the timer can be based on the SLA's elapsed
percentage (e.g., 50% of the SLA time has passed, 90% has passed).
Use Cases:
 Escalating tasks based on SLA progress. For example, if 80% of the SLA time has passed and the task
is not yet completed, you may want to escalate it to a higher priority.
 Sending notifications when a specific percentage of the SLA time has passed.
 SLA Monitoring: Ensuring that the SLA targets are met by triggering actions at specific milestones.
Example Use Case:
For an incident management workflow, you might have an SLA of 24 hours to resolve an incident. You
could set up the following steps:
1. Task Assigned (Assign incident to technician)
2. SLA Percentage Timer (Monitor the SLA progress)
 If 50% of SLA has passed, send a reminder to the technician.
 If 75% of SLA has passed, escalate the incident to a higher level.
3. Complete Task (Incident resolution)
Configuring SLA Percentage Timer:
1. Add the SLA Percentage Timer to your workflow.
2. Set the SLA definition (which SLA to monitor).
3. Define the percentage threshold (e.g., 50%, 75%) at which certain actions should be triggered.
4. Choose the next steps (e.g., escalate the task or send a notification) based on the SLA percentage.
SLA Percentage Timer activity results

Result Description

Complete The activity successfully reached the specified duration

Cancelled The activity or workflow was canceled before the timer reached the specified duration

Key Differences Between Timer and SLA Percentage Timer:


 Timer simply adds a fixed delay or wait time in the workflow.
 SLA Percentage Timer is linked to SLAs and tracks the percentage of the SLA time passed, triggering
actions based on this information.

Task workflow activities


Task activities create and modify workflow tasks.
Task activities are only available when the workflow runs on a table that extends Task.
 Add Worknote workflow activity
The Add Worknote activity adds text to the Worknotes field of the current incident record.
 Attachment Note workflow activity
The Attachment Note activity adds an attachment to the current record.
 Catalog Task workflow activity
The Catalog Task activity creates a service catalog task record.
 Create Task workflow activity
The Create Task activity generates a record on any of the tables that extend Task [task].
Branch workflow activity
The Branch activity splits the workflow into multiple transition paths from a single activity.
To add a transition path, drag the Branch activity onto the canvas. When the Branch activity properties
form displays, click Submit to add the activity to the canvas. Once the activity is on the canvas, right click
in the activity body, then click Add Condition.
All transitions from this activity execute concurrently. This activity provides a single Always condition. You
can draw any number of transitions from this condition. Using this activity is equivalent to drawing multiple
transitions from a single condition of another activity.
Join workflow activity
The Join activity unites multiple execution paths into one transition.
Use this activity to cause a workflow to wait for all activities in multiple paths to finish before continuing. If
multiple concurrent workflow paths meet without a Join activity, any subsequent activities execute twice.
To add Join to the canvas, click Submit. On the canvas, connect incoming transitions from each activity
you want to act as a predecessor to the Join activity. Then connect outgoing transitions to the two exit
conditions: Complete and Incomplete.
Results
Provide an Incomplete transition out of a Join whenever it is possible for any predecessor activities to
follow a transition path that does not lead to the Join activity.
Join activity results

Result Description

Join exits along the Complete path when the system has determined that all predecessor activiti
Complete
completed and transitioned to the Join.

Incomplet Join exits along the Incomplete path when the system determines that at least one predecessor
e completed but transitioned along a path that bypassed the Join activity.

Change policy
Notifications :- create event, notification
Service catalog :- scriptable order guide
Tasks :- attachment notes, create tasks
timers
onCall

Scheduled Jobs
Scheduled Jobs are automated pieces of work that can be performed at a specific time or on a recurring
schedule.
You can automate the following kinds of tasks:
 Automatically generate and distribute a report
 Automatically generate and schedule an entity of records, such as an incident, change item,
configuration item, from a template
 Run scheduled jobs from scripts or business rules
 Scheduling at the end of the month
 Scheduling for weekdays
Background scripts
in ServiceNow are server-side scripts that allow administrators to execute code directly on the instance's
server to perform operations that are not easily achievable through the user interface. These scripts are
especially useful for tasks like bulk updates, debugging, testing server-side code, or resolving data issues.

Uses of Background Scripts


1. Bulk Updates
Perform bulk updates on records without needing to use import sets or update sets. For example,
updating a specific field on all records in a table.
var gr = new GlideRecord('incident');
gr.addQuery('priority', 1); // Query incidents with priority 1
gr.query();
while (gr.next()) {
gr.state = 2; // Set state to 'In Progress'
gr.update();
}
2. Data Cleanup
Clean up unwanted or incorrect data in the system by removing records or modifying them

3. Troubleshooting and Debugging


Run ad-hoc scripts to test server-side code (like business rules, GlideRecord queries, or GlideAggregate
functionality) and verify their behavior.
4.  Table Schema Adjustments
Add or modify table records programmatically if the UI does not allow for certain adjustments.
5.  System Maintenance Tasks
Automate tasks like resetting flags, recalculating metrics, or fixing configuration discrepancies.
6.  Testing Code Snippets
Quickly test server-side scripts, like GlideRecord queries, GlideSystem methods, or custom script
includes.

Script Include

Script includes are used to store javascript in the server. Create script includes to store javascript functions
and classes to be run by server scripts. Each script include defines either a object class or function. Script
includes run only when called by a server script.
Script include are only accessible when called from another source:-
 Using GlideAjax on client side
 Using new javascript operator on server side
There are 2 types of script include
 Classless Script Includes:
 The name of the function and of the script include should be same.
 These scripts are server-only by default. They contain functions but do not use the Class.create()
syntax.
 Since they are not client-callable, they can only be called from other server-side scripts like Business
Rules, Scheduled Jobs, Workflows, or server-side UI Actions.
 Classless Script Includes do not support client-side calls through GlideAjax, as they don’t follow the
required structure or have the type attribute.
2. Class-Based Script Includes:
 When you create a Script Include using Class.create() and define methods within a prototype, you can
choose to make it client-callable.
 By marking a class-based Script Include as Client Callable, it becomes accessible from the client-side
through GlideAjax.
 When Client Callable is checked, the Script Include extends the AbstractAjaxProcessor class behind the
scenes, allowing it to interact with GlideAjax and handle client-server requests asynchronously.
var GetUserInfo = Class.create();
GetUserInfo.prototype = Object.extendsObject(AbstractAjaxProcessor, {
……………….
})

Extending a Script Include


To extend a Script Include, you create a new Script Include and use the extend keyword to inherit from the
existing Script Include. You can then add additional methods and properties specific to your requirements.
var ExtendedScriptInclude = Class.create();
ExtendedScriptInclude.prototype = Object.extendsObject(NameOfScriptToInclude, {
initialize: function() {
BaseScriptInclude.prototype.initialize.call(this); // Call the parent constructor
},

greetWithName: function(name) {
return "Hello " + name + ", from the Extended Script Include!";
},
type: 'ExtendedScriptInclude'
});
https://developer.servicenow.com/dev.do#!/learn/learning-plans/xanadu/new_to_servicenow/
app_store_learnv2_scripting_xanadu_script_includes
(or type service now doc script include)

Client Side vs Server Side API


Server-side APIs are not directly accessible in client scripts because client scripts execute in the user's
browser, while server-side APIs interact with the server and database.
Why Can't GlideRecord Be Used in Client Scripts?
Client scripts run in the user's browser and execute JavaScript on the client side. GlideRecord interacts
directly with the database, which requires server-side execution for security and performance reasons.
Allowing database queries from the client side would expose sensitive data and increase server load.
What Happens If You Try to Use GlideRecord in Client Scripts?
If you try to use GlideRecord directly in a client script, it will throw an error because GlideRecord is not
available in the browser's environment

Here's a table distinguishing between Client-Side APIs and Server-Side APIs in ServiceNow:
Client-Side /
API Name Description
Server-Side

Used to query, insert, update, and delete records in the


GlideRecord Server-Side
database.

Allows client-side scripts to make asynchronous calls to


GlideAjax Client-Side
server-side Script Includes.

Provides methods to manipulate forms, fields, and their


GlideForm (g_form) Client-Side
properties on the client side.

Provides methods to retrieve user information on the


GlideUser (g_user) Client-Side
client side.

Provides methods for logging, date-time manipulation,


gs (GlideSystem) Server-Side
generating unique IDs, and more.

Used to perform database aggregation queries like


GlideAggregate Server-Side
COUNT, MAX, MIN, etc.

GlideDateTime Server-Side Provides methods to manipulate date-time values.

Represents a field in a record and provides methods to


GlideElement Server-Side
interact with it.

Provides methods to work with schedules and calculate


GlideSchedule Server-Side
durations.

GlideSession Server-Side Provides methods to get session-related information like


Client-Side /
API Name Description
Server-Side

user roles and session duration.

Used in Service Portal widgets to interact with data and


GlideSPScriptable Server-Side
business logic on the server side.

Used to pass data from a server-side script (e.g., Business


g_scratchpad Both
Rule) to a client script.

GlideModal Client-Side Allows creating modal dialogs on the client side.

Similar to GlideRecord but enforces ACLs (Access


GlideRecordSecure Server-Side
Control Lists).

GlideHTTPRequest Server-Side Used to make outbound HTTP requests.

GlideEmailOutbound Server-Side Used to send email notifications programmatically.

GlideSysAttachment Server-Side Provides methods to manage attachments in records.

GlidePopup Client-Side Used to create popup dialogs.

Provides methods to get information about a table's


GlideTableHierarchy Server-Side
hierarchy.

GlideEvent Server-Side Used to generate and handle events in the platform.

Provides methods for working with Service Catalog items


g_service_catalog Client-Side
and their variables on the client side.

GlideFilter Server-Side Provides methods to apply query filters programmatically.

gs.isInteractive()
The gs.isInteractive() method in ServiceNow is used to determine whether the current script execution is
interactive or non-interactive.

Meaning of Interactive
An interactive session occurs when a user performs an action through the ServiceNow user interface (UI).
Examples include:
 Loading a form or list
 Clicking a button
 Submitting a form
A non-interactive session happens when a script or process executes without direct user interaction.
Examples include:
 Scheduled jobs
 Inbound API requests
 Background scripts
 Workflow activities
FLOW DESIGNER
Flow Designer is a powerful tool in ServiceNow that allows users to automate processes and workflows
without needing to write code. It provides a visual interface to design, manage, and automate business
processes by creating flows, which can consist of various actions, conditions, and integrations. Flow
Designer is designed to be user-friendly and accessible to both technical and non-technical users.
Key Features of Flow Designer
1. Visual Interface:
o Flow Designer uses a drag-and-drop interface, making it easy to create and visualize complex
workflows. Users can see the entire flow of actions, conditions, and triggers at a glance.
2. Actions and Steps:
o Flows consist of various actions, which can be predefined or custom. These actions include
creating, updating, or deleting records, sending notifications, and calling Script Includes or APIs.
3. Triggers:
o Flows can be triggered based on specific events, such as record creation, updates, or specific
conditions being met. Common triggers include:
 Record Inserted
 Record Updated
 Scheduled Time
4. Conditions:
o You can add conditional logic to your flows to control the flow of execution based on specific
criteria. For example, you can create branches in the workflow that execute different actions
based on the values of fields in a record.
5. Integrations:
o Flow Designer can connect to other systems and services through REST or SOAP APIs, enabling
data exchange and process automation across different platforms.
6. Reusable Subflows:
o You can create reusable subflows that can be called within other flows. This promotes reusability
and helps manage complex workflows by breaking them into smaller, manageable components.
7. Testing and Debugging:
o Flow Designer provides tools to test and debug flows, making it easier to identify issues and
optimize performance.
8. Integration with Other ServiceNow Features:
o Flows created in Flow Designer can integrate seamlessly with other ServiceNow capabilities,
such as Service Catalog, Incident Management, and Change Management.
Aspect Workflow Flow Designer

A graphical editor used for creating and A modern, codeless, and reusable process
Definition
managing workflows based on activities. automation tool for various use cases.

Automate legacy processes like approvals Simplify automation with low-code/no-code


Purpose
and tasks. tools and reusable components.

legacy product
A legacy product refers to a tool, software, or system that is still in use but has been superseded by newer,
more advanced alternatives. Although it may no longer receive updates or new features, it remains
functional and is maintained primarily to support existing implementations or use cases.
Key Characteristics of a Legacy Product:
1. Superseded by Modern Tools:
o A newer solution, like Workflow Studio in this case, has been introduced to replace the older
tool (Workflow Editor).
2. Maintenance, Not Enhancement:
o The legacy product is supported only for bug fixes or critical updates, ensuring stability for
existing users but not for innovation or new features.
3. Backward Compatibility:
o Maintained to allow organizations with established workflows to continue operations without
disruption or the need for immediate migration.
4. Transition Encouraged:
o Users are typically encouraged to transition to the newer solution (e.g., from Workflow Editor to
Workflow Studio) to take advantage of improved functionality and support.
Relationship
Today I learned something new. I learned about Relationships (sys_relationship) table. I know many of you
might already be aware of this functionality but for me it was new, and I thought of sharing it in my article
below.
Related Lists: These are the lists which appear at the bottom of a form when there is some relationship
present in between those two tables. A relationship could be of any type. One to one, one to many, many to
many and scripted relationship.
So far, I was aware of One to one/One to many and Many to Many relationships only and for these
relationships to be present there should be a direct connection between the two tables. Like a parent child
relationship where one table is directly referencing other.
Then I came across a use case where I had to create a related list on a table which is not directly connected
to the other table. For e.g. I want to display the list of requests as related list on incident table which were
requested for the same caller. Now in this case Incident and Requests are not directly connected to each
other, but they have a common reference to ‘sys_user’ table with the help of ‘caller_id’ and ‘requested_for’
fields respectively. So I could not configure a related list directly and had to go with the scripted approach.
Here comes the Defined Related lists into picture. In order to achieve this we need to create a related list in
Relationships(sys_relationship) table. Below are the steps we will follow to achieve the same.
1. Go to left Nav and look for System Definition->Relationships.
2. Click New and fill the form as shown below and hit submit:

Here, Applies to table: will be the table on which you want to create the related list.
Queries from table: will be the table from which we want to display the data as a related list.
Query with: In this script section we will write the query or logic we want to perform to get the data from
sc_requests. Clearly it is possible to add multiple queries here or write encoded query as well.
3. Once done then we need to go to incidents and configure this related list on incident table. In order to
configure the related list, we need to right click on the form header and select Configure-> Related lists.
After this we need to pick the specific related list from left slush bucket and place it into right slush
bucket and save as shown in below steps:

Note-
 The Edit button is not available on defined relationships, as the relationship is scripted.
 Some many-to-many relationships are defined by default.
 To reference many-to-many relationships that are available in the base system, administrators can
enter sys_collection.list in the navigation filter.

 Note: Only use this table to view many-to-many relationships in the base system. To create a new relationship,
always use the Many-to-Many Definitions table.

 https://www.servicenow.com/docs/bundle/xanadu-platform-user-interface/page/administer/form-
administration/task/t_CreateDefinedRelatedLists.html

Data Lookup
The data lookup and record matching feature enables administrators to define rules that automatically set one or
more field values when certain conditions are met.
Data lookup rules allow administrators to specify the conditions and fields where they want data lookups to
occur. For example, on Incident forms, there are priority lookup rules for the sample data that automatically set
the incident Priority based on the incident Impact and Urgency values
Steps:
Create a custom table to store lookup data.
The custom table must extend the Data Lookup Matcher Rules [dl_matcher] table.
Step 1: Create the Matcher Table (if not done yet)
1. Create a Table:
o Go to System Definition > Tables.
o Click New to create a table (e.g., Incident Category Mapping).
o Define fields such as:
 Category (String or Choice).
 Assignment Group (Reference to the Group table).
2. Populate the Matcher Table:
o Add records mapping categories to their corresponding assignment groups.
Step 2: Create the Data Lookup Definition
1. Navigate to: System Policy > Data Lookup Definitions.
2. Click on New to create a new Data Lookup Definition.
3. Fill in the Data Lookup Definition:
o Name: Give it a descriptive name (e.g., "Assign Group Based on Category").
o Source Table: Select Incident.
o Matcher Table: Choose your matcher table (e.g., Incident Category Mapping).
Step 3: Configure Matcher and Setter Field Definitions
In the Data Lookup Definition form, you should see sections for Matcher Field Definitions and Setter Field
Definitions. Here’s how to configure them:
1. Matcher Field Definition:
o Field: Select the field in the source table (Incident) that you want to match against the matcher
table (e.g., Category).
o Matcher Table Field: This should reference the corresponding field in your matcher table that
contains the categories (e.g., Category in Incident Category Mapping).
Example:
o Field: Category
o Matcher Table Field: u_category (or whatever you named the field in the matcher table).
2. Setter Field Definition:
o Field: Select the field in the source table (Incident) that you want to set automatically (e.g.,
Assignment Group).
o Setter Table Field: This should reference the corresponding field in your matcher table that
contains the assignment groups (e.g., Assignment Group in Incident Category Mapping).
Example:
o Field: Assignment Group
o Setter Table Field: u_assignment_group (or whatever you named the field in the matcher table).
Step 4: Save and Test
1. Save your Data Lookup Definition.
2. Create a new incident:
o Go to Incident > Create New.
o Select a Category that matches one of your entries in the matcher table.
o Check if the Assignment Group field is automatically populated based on your Data Lookup
Definition.
Service Portal
 Increase accuracy and speed
Build end-to-end self-service portals quickly and smoothly with an easy-to-use, modular UI.
 Create engaging experiences
Technologies it use – html,css, javascript, angular, bootstrap
A Service Portal in ServiceNow is a user-friendly, self-service interface designed to provide a seamless and
intuitive experience for users to access and interact with the services, resources, and information they need. It
serves as a modern, customizable front-end to the ServiceNow platform, allowing users to perform tasks such
as submitting requests, searching for knowledge articles, reporting incidents, and accessing various resources.

Key Features of Service Portal:


1. Customizable Interface:
o Allows administrators to design and modify the portal's look and feel.
o Branding options like themes, colors, and logos.
2. Widget-Based Architecture:
o Uses reusable components called widgets to display content and functionality.
o Widgets can be customized or built from scratch.
3. Responsive Design:
o Optimized for different devices, including desktops, tablets, and smartphones.
4. Integration with ServiceNow Modules:
o Service Catalog: Users can request items, services, or software.
o Knowledge Base: Users can search for and view knowledge articles.
o Incident Management: Users can log and track incidents.
o Dashboards and reports for analytics.
5. User-Centric Navigation:
o Provides intuitive navigation through menus, search functionality, and typeahead suggestions.
6. Secure Access:
o Role-based access ensures users only see content and functionality relevant to them.

Pages
Each portal is made up of one or more pages. Pages are not unique to a portal and can be used in as many
portals as needed. A portal applies theming, a header, a footer, and some additional metadata to a page, allowing
reuse without changes to a page's definition.
Containers
Portal pages are organized by containers. Containers create the page layout by organizing pages into sections.
Containers are divided into rows. Containers typically contain a single row but can have multiple rows. Each
row has a specified number of columns. Each row can contain a different number of columns.
Widgets
Widgets are reusable components that make up the functionality of a portal page. They consist of HTML
markup, CSS, a JavaScript controller, and client-side and server-side code. Widgets define what a portal does
and what information a user sees. ServiceNow provides a large number of baseline widgets. Examples include:
 Approvals
 Knowledge Base
 My Requests
 Carousel
 Catalog content
 Popular questions
 Search
DEVELOPER TIP:
 When creating Portals, specify which Knowledge Bases and Catalogs to include. If no Knowledge
Bases or Catalogs are specified for a portal, the portal uses all Knowledge Bases and all Catalogs.
 In ServiceNow's Service Portal, you can assign roles to widgets to control which users can view and
interact with those widgets. This ensures that only users with the specified roles can access the widget's
content.

Create an announcement
An announcement appears as a banner in Service Portal or within the announcements widget.
https://www.servicenow.com/docs/bundle/washingtondc-platform-user-interface/page/build/service-portal/
task/create-announcement.html
Inbound Integration
Inbound integration involves receiving data or requests from external systems into ServiceNow. This can be
done through various methods, including:
1. REST APIs:
o ServiceNow can expose RESTful APIs that allow external systems to send requests to
ServiceNow.
o Example: An external application creates an incident in ServiceNow by sending a POST request
to a Scripted REST API endpoint.
2. SOAP APIs:
o Similar to REST, ServiceNow can also expose SOAP web services for external systems to
interact with.
o Example: An external system updates a record in ServiceNow using a SOAP request.
3. Email Integration:
o ServiceNow can process incoming emails to create or update records based on specific rules.
o Example: Sending an email to a predefined address can create an incident in ServiceNow.
4. Import Sets:
o Data can be imported into ServiceNow from external sources using import sets.
o Example: A CSV or Excel file containing user data is imported into the User table.
5. Data Sources and Transform Maps:
o ServiceNow can connect to external databases or services to retrieve data.
o Example: Using a JDBC connection to fetch data from an external SQL database.
Outbound Integration
Outbound integration involves sending data or requests from ServiceNow to external systems. This can be done
through several methods, including:
1. REST APIs:
o ServiceNow can send HTTP requests to external RESTful APIs to share data or trigger actions.
o Example: A Business Rule triggers a REST API call to an external service to notify about a
newly created incident.
2. SOAP APIs:
o Similar to inbound, ServiceNow can also send SOAP requests to external systems.
o Example: A Script Include sends a SOAP request to an external system to retrieve information.
3. Email Notifications:
o ServiceNow can send emails to external recipients based on specific events or conditions.
o Example: Sending an email notification to a support team when a critical incident is reported.
4. IntegrationHub:
o ServiceNow's IntegrationHub provides a way to build and manage integrations with external
systems through connectors and flows.
o Example: Using IntegrationHub to connect ServiceNow to third-party applications like Slack or
Salesforce.
5. Webhooks:
o ServiceNow can be configured to send data to external systems in real-time through webhooks.
o Example: A webhook triggers an external system to update its records when an incident is
closed.
Scripted RestApi
A Scripted REST API in ServiceNow allows developers to create custom REST endpoints to expose
ServiceNow functionality to external systems or perform custom actions. These APIs can be tailored to meet
specific requirements that out-of-the-box REST APIs cannot handle.
In simple terms:
 REST API: A way for applications to communicate with each other using HTTP methods like GET,
POST, PUT, and DELETE.
 Scripted REST API: A customizable REST API in ServiceNow where you define the logic for handling
incoming requests and generating responses using server-side scripts.
How Scripted REST API Works
1. Request:
o A client (external application) sends an HTTP request to the API endpoint. The request includes
HTTP methods (GET, POST, PUT, DELETE) and optional data like parameters, headers, or
payloads.
2. Processing:
o The Scripted REST API processes the request using the logic defined in a script. It may interact
with ServiceNow tables, run scripts, or perform other operations.
3. Response:
o The API sends a response back to the client. The response includes a status code (e.g., 200 for
success, 404 for not found) and optional data.
Example :-
 API Name: Incident API.
 Resource Path: /getIncident.
 HTTP Method: GET.

(function process(request, response) {


var gr = new GlideRecord('incident');
gr.addQuery('number', request.pathParams.number);
gr.query();
if (gr.next()) {
response.setBody({
number: gr.number.toString(),
short_description: gr.short_description.toString(),
});
} else {
response.setStatus(404);
response.setError("Incident not found");
}
})(request, response);

1. Base Path
The base path is the foundational part of the URL that serves as the starting point for accessing an API or a set
of resources. It usually remains constant and provides a general context or grouping for API endpoints.
 Defined by: The API or application hosting the resources.
 Example in Scripted REST APIs:
o /api/incident could be the base path for APIs related to incident management.
o For example, the full API URL might be:
 Purpose:
o Groups related API resources together.
o Provides a consistent starting point for API consumers.
2. Relative Path
The relative path specifies a particular resource or action relative to the base path. It is appended to the base
path to create the complete endpoint for a specific operation.
 Defined by: The specific endpoint or operation within the API.
 Example in Scripted REST APIs:
o /getIncident could be the relative path for fetching details of a specific incident.
o Full API URL:
 Purpose:
o Identifies a specific action or resource within the broader context of the base path.

Aspect Base Path Relative Path

Definition Foundational part of the URL Specifies a resource/action within the base path

Purpose Groups related endpoints Targets a specific resource or functionality

Changes? Rarely changes Varies for different endpoints

Example /api/incident /getIncident


Path Parameter vs Query Parameter
Path parameters and query parameters are ways to pass data to an API endpoint, but they serve different
purposes and are used in different contexts. Here’s a detailed comparison:

1. Path Parameter
Path parameters are part of the URL path and are typically used to identify a specific resource or entity.
 Format:
o Included as part of the URL path.
o Encased in curly braces {} in the API definition.
 Use Case:
o Used for required parameters.
o Typically identifies a specific resource or entity.
 Example:
o Endpoint: /users/{userId}/orders/{orderId}
o Full URL: /users/123/orders/456
 userId = 123
 orderId = 456
 Key Features:
o Mandatory in most cases.
o Helps define the hierarchy of resources.
Accessing Path Parameters

Path parameters and query parameters are usually extracted from the URL in the script. For example, in a
ServiceNow Scripted REST API:

GET /api/now/table/incident/{incidentId}

Here, {incidentId} is a path parameter.

Script:-
var incidentId = request.pathParams.incidentId;

2. Query Parameter
Query parameters are appended to the URL after a question mark ? and provide additional information or filters
for the API request.
 Format:
o Key-value pairs separated by = and joined by &.
o Appended to the URL after ?.
 Use Case:
o Used for optional parameters.
o Filters, sorting, pagination, or additional instructions.
 Example:
o Endpoint: /users/orders
o Full URL: /users/orders?status=shipped&sort=date
 status = shipped
 sort = date
 Key Features:
o Optional in most cases.
o Can have multiple parameters.

 Define Query Parameters in the API Resource:


 When creating a Scripted REST API, you can define query parameters in the URL like ?
priority=1&state=Open.
 Access Parameters in the Script:
 Use request.queryParams.<parameterName> to retrieve the values passed in the URL.
 Use Query Parameters in Your Logic:
 Filter records or perform operations based on the values of the query parameters.

Yes, you can use the Scripted REST APIs you create in ServiceNow within Business Rules or Script Includes.
Here's how you can integrate them in both contexts:
Using APIs in Business Rules
1. You can call your Scripted REST API using a standard HTTP request. You can use the
sn_ws.RESTMessageV2 class to make a call to your API endpoint from within a Business Rule.
// Business Rule to call a Scripted REST API when an incident is created
(function executeRule(current, previous /*null when async*/) {
// Create a REST message
var restMessage = new sn_ws.RESTMessageV2();
restMessage.setEndpoint('https://<instance_name>.service-now.com/api/<namespace>/incident/
createIncident');
restMessage.setHttpMethod('POST');
restMessage.setRequestHeader('Content-Type', 'application/json');
restMessage.setBasicAuth('<username>', '<password>'); // Use appropriate authentication
// Set the request body
var requestBody = {
"short_description": current.short_description,
"description": current.description,
"caller_id": current.caller_id.sys_id // Assuming caller_id is a reference field
};
restMessage.setRequestBody(JSON.stringify(requestBody));

// Send the request and handle the response


var response = restMessage.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();

// Handle the response as needed


gs.info('API Response: ' + responseBody);
gs.info('HTTP Status: ' + httpStatus);
})(current, previous);

sn_ws.RESTMessageV2
sn_ws.RESTMessageV2 is a ServiceNow class used to create and send REST API requests. It is part of the
ServiceNow scripting environment and is primarily used for outbound integrations, allowing ServiceNow to
communicate with external systems via RESTful APIs.
Key Features of sn_ws.RESTMessageV2
1. Creating REST Requests: The class allows you to create HTTP requests (GET, POST, PUT, DELETE)
to interact with external REST APIs.
2. Setting Request Parameters: You can set various parameters for the request, including headers, query
parameters, request body, and authentication methods.
3. Sending Requests: Once the request is configured, you can send it and receive a response from the
external system.
4. Handling Responses: You can handle the response returned by the API, including checking the status
code, reading response body, and processing the data.

Example Use Cases


 Integrating with Third-Party Services: Use sn_ws.RESTMessageV2 to pull or push data to external
services like Salesforce, Slack, or external databases.
 External Notifications: Send alerts or notifications to external systems based on certain events or
conditions within ServiceNow.
 Data Synchronization: Regularly fetch or update records in external systems to keep data in sync.

1. REST API Message (Outbound Integration):


 Purpose: Used for outbound integrations where the ServiceNow instance communicates with external
systems.
 How it works:
o You configure a REST Message in ServiceNow to define how the instance makes requests to
external APIs.
o It specifies details such as the endpoint URL, HTTP method (GET, POST, etc.), request headers,
query parameters, and authentication.
2. Scripted REST API (Inbound Integration):
 Purpose: Used for inbound integrations where external systems communicate with the ServiceNow
instance.
 How it works:
o You define custom endpoints and logic using a Scripted REST API in ServiceNow.
o It allows external systems to send requests (like GET or POST) to your ServiceNow instance.
o You can process incoming data, query the ServiceNow database, or perform specific actions.
 Example Use Case: Allowing an external system to create incidents in ServiceNow or fetch user
information.

Example: ServiceNow Integration with a CRM (Salesforce)


Scenario:
A company wants to integrate ServiceNow with Salesforce to synchronize customer data and manage support
tickets efficiently. The integration ensures that when a customer logs an issue in Salesforce, a corresponding
incident is created in ServiceNow automatically.

How it Works:
1. REST API for Data Exchange:
 Requirement: When a new case is created in Salesforce, it should trigger the creation of an incident in
ServiceNow.
 Solution:
o Salesforce uses a webhook (outbound message) to notify ServiceNow via its REST API.
o ServiceNow exposes its REST API endpoint to receive the webhook data and create the
incident.
Example API Call:
 Endpoint: https://instance.service-now.com/api/now/table/incident
 Method: POST
  Headers:
{
"Authorization": "Bearer <access_token>",
"Content-Type": "application/json"
}
 Payload
{
"short_description": "Customer reported issue from Salesforce",
"description": "Details of the issue...",
"caller_id": "Customer Name",
"priority": "2"
}
Script Example
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
var requestBody = request.body.data;
var incidentGr = new GlideRecord('incident');

incidentGr.initialize();
incidentGr.short_description = requestBody.short_description;
incidentGr.description = requestBody.description;
incidentGr.priority = mapPriority(requestBody.priority); // Custom mapping function
incidentGr.insert();

response.setBody({ status: "Incident created successfully!" });


})(request, response);

function mapPriority(priority) {
switch (priority) {
case 'High': return 1;
case 'Medium': return 2;
case 'Low': return 3;
default: return 4; // Default priority
}
}

Outcome:
 Automation: Whenever a case is created in Salesforce, ServiceNow creates a corresponding incident
without manual intervention.
 Custom Logic: Business-specific requirements like priority mapping are handled via Scripted APIs.
 Seamless Communication: The REST API facilitates real-time, reliable communication between
Salesforce and ServiceNow.

How to load data from data source to staging table using script
var loader = new GlideImportSetLoader();
✅ Creates an instance of the GlideImportSetLoader class.

This class is used for loading data from a data source into an import set table.
It does not perform transformations—just loads data into the staging table.
var importSetGr = loader.getImportSetGr(dataSource);
✅ Calls the getImportSetGr(dataSource) method of GlideImportSetLoader.

dataSource is the sys_id of the Data Source record that contains the attachment.
This retrieves or creates a new import set record (sys_import_set table).
The returned importSetGr is a GlideRecord representing that import set.
loader.loadImportSetTable(importSetGr, dataSource);
✅ Calls the loadImportSetTable(importSetGr, dataSource) method.

This loads the data from the given dataSource into the import set table associated with importSetGr.
The data from the attached file in the data source is parsed and inserted into the import set table.
No transformation occurs at this step; the data is only staged for further processing.
🔍 Example Workflow:
User uploads an Excel file → It gets stored in sys_attachment and linked to a Data Source (sys_data_source).
This script runs:
Finds the Data Source (dataSource).
Retrieves or creates an import set record (importSetGr).
Loads the data from the attached Excel file into the import set table (sys_import_set_row).
Data is now stored in Import Set Rows, ready for manual verification or transformation.
Problem Statement:-
Techmania is a company that manufactures AI devices, it takes orders from clients through chat, phones,
and emails. Order process is currently managed through spreadsheets. DM team emails the release
management team for approval. Dispatch management team handles outsource management based on
approval.
Problem solved:-
Automatic notification to user.
Clients can directly order through service portal
Faster approvals
Single page from where multiple things can be ordred
Dashboard to track the order status

Three roles and three groups are created


Device manager
Dispatch Manager
Release manager
Two Tables
AI devices
Device Request
AI devices
Read – all
Write, Create, Delete – Device Manager
Device Request
Read – all
Write – Device Manager, Release manager
Create, Delete – Device Manager

Requirement
If quantity is more than 2 make description mandatory
If device name is not selected device details and delivery details are not visible(Client script, device request
table)
If device name is selected device details and delivery details should be visible and the device details should
get filled with detail from ai device table (Client script, device request table)
Catalog item
The requestor name automatically gets filled with the name of current user
The quantity field should only contain number if it contains something else a message will be shown (client
script)
If quantity>2 set business justification as mandatory.
Add a field total field which is automatically calculated when quantity is modified.(catalog client script)

Catalog item flow


ServiceNow Topics:
 Workflows
 Creating and managing workflows using Workflow Editor and Flow Designer.
 Understanding activities.
 Notifications
 Events
 Inbound and Outbound Integration
 REST Message
 Creating REST messages for outbound API calls.
 Configuring and testing REST message properties.
 Scripted REST API
 Developing custom REST APIs using scripted resources.
 Defining endpoints and response formats.
 REST API Explorer
Exploring available APIs and testing API calls using the REST API Explorer.
 Service Catalog
 Creating catalog items.
 Integrating workflows with service catalog items.
 Client-Side Scripting
 UI Policies, Client script, Catalog Client script
 Server-Side Scripting
 business rules, UI Actions and script includes.
 Access Control
 Service Level Agreements (SLA)
 Import Set, Transform Map
 Report and Dashboard
 Custom Application Development
 Building custom applications within ServiceNow to meet business needs.
 Inbound Email Action
 Configuring inbound email actions to process incoming emails and update records.
ServiceNow Topics:
Workflows
Notifications
Events
Inbound and Outbound Integration
REST Message
Scripted REST API
REST API Explorer
Service Catalog
Client-Side Scripting
Server-Side Scripting
Inbound Email Action
Access Control
Service Level Agreements (SLA)
Import Set, Transform Map
Report and Dashboard
Custom Application Development

You might also like