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

Business Rule Complete Notes

Servicenow business rule

Uploaded by

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

Business Rule Complete Notes

Servicenow business rule

Uploaded by

Gaurav Bhoyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Business Rule

Glide Record API

It is a server-side API • It is used for database Operation.

• The Glide Record API is a primary means of interfacing with the database on the server-side code.
• A Glide Record is a Object that contain Record from single table [EX= incident , problem , change
etc].

• Use this API to represent a Glide Record & add Query parameter, filter, Limit, Ordering etc…

Working with query() method

• var inc = new GlideRecord ('incident’) //GlideRecord is main Oject and Incident is Table

• inc.query (); //Query is execute in the table

• while (inc.next ()) { //Loop will runs on the table

• gs.print (inc.number); //Printing all incidets

•}

• Result:- Print all records numbers in Incident Table

Display priority -1 tickets from incident table with addQuery methods

• var inc = new GlideRecord ('incident');

• inc.addQuery ('priority=1');// Add the query

• inc.query ();

• while(inc.next()){

• gs.print(inc.number);

•}

• Result:-Printing all prority-1 tickets

Passing Multiple Queries using by same methods

• var inc = new GlideRecord('incident');

• inc.addQuery ('active', true); //Query 1

• inc.addQuery ('priority=1'); //Query 2

• inc.addQuery ('category','software'); //Query 3

• inc.query ();

• while(inc.next()){

• gs.print (inc.number);
•}

• Result:- Print all records where your Condition meet

we can use addEncodedQuery method Instead of passing multiple queries into our script

• Step-1: Navigate to Incident list view and apply condition

• Step-2: Condition: active = true and priority =1 and category = software

• Step-3: Click on Run

• Step-4: Copy applied query through Copy query

• Step-5: Use this entire query into your script

• Step-6: Script

• var inc = new GlideRecord ('incident'); •


inc.addEncodedQuery('active=true^category=software^priority=1');

• inc.query();

• while(inc.next()){

• gs.print(inc.number);

•}

Working with addQuery (‘String’,’Operator’,’Value’)

•=

• !=

•>

• >=

•<

• <=

• Strings (must be in upper case):

•=

• !=

• IN

• NOT IN

• STARTSWITH

• ENDSWITH

• CONTAINS

• DOES NOT CONTAIN


• INSTANCEOF

Get Active and Priority is less than or equal to 2

• var inc = new GlideRecord('incident');

• inc.addActiveQuery();

• inc.addQuery('priority','<=',2);

• inc.query();

• while(inc.next()){

• gs.print(inc.number);

•}

Result:-Print Critical-1 and High-2 tickets

Working with SQL operators <= and CONTAINS

var inc = new GlideRecord('incident');

• inc.addActiveQuery();

• inc.addQuery('priority','<=',2);

• inc.addQuery('short_description','CONTAINS’,’test’);

• inc.query();

• while(inc.next()){

• gs.print(inc.number + ' ' + inc.short_description);

•}

Result:-Print all records where our condition meet like (<=2 and CONTAINS)

Working with IN operator and print category of Software and Hardware

• var cat = ['software', 'hardware'];

• var inc = new GlideRecord('incident');

• inc.addQuery('category', 'IN', cat);

• inc.query();

• while(inc.next()) {

• gs.print(inc.getValue('number') + ' ' + inc.getValue('short_description')) ;

•}

• Result:-Print where category is Software ad Hardware

Display all records in order wise (Assending) it depends on field values.

• var inc = new GlideRecord('incident');


• inc.addQuery('priority=1');

• inc.addQuery('category=software');

• inc.orderBy('short_description');

• inc.query();

• while(inc.next()){

• gs.print(inc.number + ' ' + inc.short_description);

•}

• Result:-Print all incidents order wise depends on Short Description

Display limited records from specified table

• var inc = new GlideRecord('incident');

• inc.addQuery('priority=1');

• inc.orderByDesc('short_description');

• inc.setLimit(10);

• inc.query();

• while(inc.next()){

• gs.print(inc.number + ' ' + inc.short_description);

•}

• Result:- Print only latest 10 records created from given table

Working with initialize () and insert () method

These methods are used to Inserts a new record using the field values that have been

set for the current record

var inc = new GlideRecord ('incident');

• inc.initialize (); //Compose incident form

• inc.category = ‘network’; // set field values

• inc.short_description = ‘Firewall Issue’;

• inc.priorty = 1;

• inc.insert (); // create new record

• gs.print (inc.number);// print new record incident number


For more check below link :
https://developer.servicenow.com/dev.do#!/reference/api/vancouver/server_legacy/c_GlideReco
rdAPI

Business Rule:- 1. A business rule is a server-side script that runs when a record is displayed,
inserted, updated, or deleted, or when a table is queried.
2.Table of business rule:- sys_script .

Four type of business rule.

1. before business rule.


2. after business rule.
3. async business rule.
4. display business rule.

Database Operation :

1. Insert:- When the user creates a new record and the system inserts it into the database.
2. Update :- When the user modifies an existing record.
3. Query :- Before a query for a record or list of records is sent to the database. Typically
you should use query for before business rules.
4. Delete :- When the user deletes a record.

Two steps of business rule

• When to run
• Action

Global Variable

• Current: Current state of the record being referenced. See "Prevent null pointer
exceptions" below to check for nulls before using this variable.
• Previous: If multiple updates are made to the record within one execution context,
previous will continue to hold the state of the record before the first update or delete
operation. Available on update and delete operations only. Not available on async
operations. See "Prevent null pointer exceptions" below to check for nulls before using
this variable.
• G_scratchpad: Scratchpad object is available on display rules, and is used to pass
information to the client to be accessed from client scripts.
• Gs: glide system
Business rule processing flow

Prevent recursive business rules

Avoid using current.update() in a business rule script. The update() method triggers business rules
to run on the same table for insert and update operations, leading to a business rule calling itself
over and over. Changes made in before business rules are automatically saved when all before
business rules are complete, and after business rules are best used for updating related, not
current, objects. When a recursive business rule is detected, the system stops it and logs the error
in the system log. However, current.update() causes system performance issues and is never
necessary.

You can prevent recursive business rules by using the setWorkflow() method with the false
parameter. The combination of the update() and setWorkflow() methods is only recommended in
special circumstances where the normal before and after guidelines mentioned above do not
meet your requirements.

Before Business Rule :


Before Business Rule execute before data save into the database or table.
Step Of Execution :
Record get Save into Database or Table
Before Business Rule will get Execute
When user click save or update record
Example : Check the current value of state, if not equal to previous value then set impact high .
When to run select before and action is insert or update.

Name: incident query


Table: Incident
When: before, insert,update
Script:
(function executeRule(current, previous /*null when async*/)
if('current.state'!='previous.state')

current.impact=’1’;

current.update();

})(current, previous);

After Business Rule :-


After Business Rule Execute after the action perform on database or table.Whent data saved
into database then after business rule Run.
Step Of Execution :
When user click save or update the record
Record get save into database or table
After Business Rule Script Will get Execute
Example :- When Problem is created related Incident state change to “On hold” and onhold
reason “Awaiting Caller”
select table problem and apply after business rule perform action insert and update

Name: incident query


Table: Incident
When: After,insert ,update
Script:
(function executeRule(current, previous /*null when async*/) {

var gr = new GlideRecord('incident');

gr.addActiveQuery(); //Cross check only active incidents

gr.addQuery('problem_id', current.sys_id);

gr.query();

while (gr.next()) {

gr.state='3';

gr.hold_reason='1';

gr.update();

})(current, previous);
Async Business Rule :-
Async Business Rule Execute after the action perform on database or table.Whent data saved
into database then Async business rule Run. Async Business Rule task are independent to
each other.They are run simultaneouly reduce the redandency.
Step Of Execution :
When user click save and update the record

Record get save into database or table

Aync Business Rule Script will get execute

Example :- When assignment group changes then update the task SLA group to current
assignment group .

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

var value = current.u_company

// Add your code here

var gr = new GlideRecord('u_gliderecord');

gr.initialize();

gr.u_company= value;

gr.insert();

})(current, previous);

Display Business Rule :-


1.display business rule provide client script access from server side data.

2. Display business rule is triggered whenever a user open / loads form.

Example :-Populate the caller email id if incident has any attachment.


Display Business Rule
(function executeRule(current, previous /*null when async*/) {
g_scratchpad.hasAttachments = current.hasAttachments();
g_scratchpad.email=current.caller_id.email.getDisplayValue();
})(current, previous);
Client Script
function onLoad() {
var email=g_scratchpad.email;
if(g_scratchpad.hasAttachments){
alert("Caller Email name==="+email);
}
}

Query Business Rule :Query business rule alternative way of ACl in query business it gives
limited access to particular user.

Example :prevents users from accessing incident records unless they have the itil role, or are
listed in the Caller or Opened by field. So, for example, when self-service users open a list of
incidents, they can only see the incidents they submitted

• Name: incident query


• Table: Incident
• When: before, query
• Script:

.if(!gs.hasRole("itil") && gs.isInteractive()) {


var u = gs.getUserID();
var qc =
current.addQuery("caller_id",u).addOrCondition("opened_by",u).addOrCondition("watch_list","CO
NTAINS",u);
gs.print("query restricted to user: " + u);
}

Example

When priority 1 incident from create problem related to it.

After Br

Condition: priority changes to critical

Var prb = newGlideRecord (‘problem’);

prb.initialize();

prb.first_reported_by_task=current.sys_id;

prb.short_description=current.short_description;

prb.description=current.short_description;

prb.assignment_group=current.assignment_group;

prb.insert();
Create a problem record on incident form related tab

After Br

Var prb = newGlideRecord (‘problem’);

prb.initialize();

prb.short_description=current.short_description;

prb.description=current.short_description;

prb.insert();

current.problem_id=prb.sys_id;

current.update();

When problem state changes to resolved all incident related to it get closed

After Br

Condition: State changes to Resolved

Var inc= newGlideRecord (‘incident’);

Inc.addQuery(‘problem_id’,current.sys_id);

Inc.query();

While(Inc.next()){

Inc.state=6;

Inc.close_code =’Resolved by problem’;

Inc.update();

What is the difference between after and asynch BR?

After BR : This type of BR is used when some field changes needs to be reflected immediately
after user saves the record. Mostly used to update/insert record into another table once
insert/update/delete operation is performed on current record.

Below is an example where After BR can be used

- On reassignment of incident, add comments in associated problem record.


Asynch BR : As name suggest, it runs asynchronously. Whenever Asynch BR is triggered, system
creates new entry in event queue to process. Execution time varies for Asynch BR based on the
load on event queue.

What are the different objects accessible in BR?

- Current

- Previous

- gs

- g_scratchpad

Note: Previous object is null in Asynch BR, as there could be multiple updates on same record
while BR is in queue for execution which might create conflict on which version needs to be
considered as previous.

What is display BR? When to use it? Explain with real time use case?

Display rules are processed when a user requests a record form. The data is read from the
database, display rules are executed, and the form is presented to the user.

The primary objective of display rules is to use a shared scratchpad object, g_scratchpad, which is
also sent to the client side as part of the form. This can be useful when you need to build client
scripts that require server data which is not typically part of the record being displayed.

Real time use case : If logged in user is member of current assignment group then only show
description field.

We can write display BR as shown below to check if logged in user is part of current group or not
and store result in g_scratchpad object, which later can be accessed in client script to show/hide
description field accordingly.

What is the difference between query BR and ACL?


1.Query business rules only apply for read access at the row level while ACLs can do CRUD
operation at the row and column level.

2. Query BRs will affect a GlideRecord query result where ACLs will not unless we are using
GlideRecordSecure class.

3. Query BR shows only those records where filter criteria matched while ACL shows all pages
with the restricted records being invisible and a message at the bottom 'some records removed
due to security'.

What are global Business Rules?

A global Business Rule is a Business Rule where the selected Table is Global. Any other script can
call global Business Rules. Global Business Rules have no condition or table restrictions and load
on every page in the system.

How to prevent form submission via Business Rule?

We can use 'current.setAbortAction(true)' in Business Rule script to abort action. This will stop
data updation in database.

How to identify if current operation is insert, update or delete in Business Rules?

We can use current.operation() in BR. Depending on current operation, it returns update, delete
or insert value.

How to trigger notification via Business Rules?

We can use gs.eventQueue method to trigger notification via business rule.

Syntax : gs.eventQueue('event_name',current,'param1','param2');

What is GlideRecordSecure? What is the difference between GlideRecord and


GlideRecordSecure:

Answer: GlideRecordSecure is a version of GlideRecord that provides an additional layer of


security. GlideRecordSecure is designed to prevent unauthorized access to data.
GlideRecordSecure enforces access controls and ensures that the user has permission to access
the records they are querying. Developers can then use GlideRecordSecure in the same way as
GlideRecord to query and manipulate ServiceNow records.

GlideRecord queries and manipulates data in the same way as GlideRecordSecure, but
GlideRecordSecure provides additional features for securing sensitive data. This ensures that
sensitive data cannot be intercepted by unauthorized users as it enforces access controls.
Another difference between the two is performance, Because GlideRecordSecure enforces access
controls, it may take longer to execute queries than GlideRecord.

You might also like