Service Now Developer
Service Now Developer
NOTE:-
While you are working with scripts, labels are not used instead their values are used. For example
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
……………………………
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:
Method Description
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)
next Moves to the next record in the result set. Returns boolean
Inserts the new record into the database and returns the new
insert
sys_id.
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()
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
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
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 an informational
gs.info(message) gs.info("Info message");
message.
Adds an informational
gs.addInfoMessage(message) gs.addInfoMessage("Info message");
message to the UI.
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.save() Saves the form without navigating away from the page.
g_form.addOption(fieldName, choiceValue,
Adds a new option to a choice field.
choiceLabel)
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.
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');
}
Method Description
g_user.getUserID() Returns the user ID of the currently logged-in user (e.g., sys_id).
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.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.savePreference(name,
Saves a user preference with a given name and value.
value)
false.
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.
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
Subtracts another GlideDateTime object from the current object and returns the
subtract(GlideDateTime)
difference.
getEffectiveDisplayValue() Returns the effective display value considering the user's locale and time zone.
Eg
1.
var gd1 = new GlideDateTime();
gs.print(gd1);
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.
if (date1.before(date2)) {
gs.info('Date1 is before Date2');
}
if (date2.after(date1)) {
gs.info('Date2 is after Date1');
}
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()
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);
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.
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
📌 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
📌 Syntax
modal.setPreference("key", "value");
🔹 "key" → Name of the preference (parameter)
🔹 "value" → Value assigned to the preference
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();
}
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.
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) {
if (current.priority == 1) {
} else {
})(current, g_scratchpad);
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();
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.
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.
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.
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.
Operation Description
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.
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.
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.
When ordering a laptop, a form collects one-time input for "User's Name",
"Department", and "Reason for Request".
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.
Clone a request
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.
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:
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.
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.
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
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.
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).
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.
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.
Field Description
States
The activity state tells the workflow engine what to do with the activity.
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
Cancelled The activity or workflow was canceled before the timer reached the specified duration
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.
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, {
……………….
})
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)
Here's a table distinguishing between Client-Side APIs and Server-Side APIs in ServiceNow:
Client-Side /
API Name Description
Server-Side
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.
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.
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.
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.
Definition Foundational part of the URL Specifies a resource/action within the base path
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}
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.
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));
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.
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();
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
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)