business rules in servicenow

0
1586

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. We use business rules to achieve tasks such as create events for email notifications and script actions.

Business Rule overview

What is business rule?

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.

When business rules run

Business rules run based on two sets of criteria:

    • The time that the business rule is configured to run relative to a record being modified or accessed.
    • The database operation that the system takes on the record.

 

How to navigate to business rule in ServiceNow

    1. Go to System Definitions > Business Rules.
    2. Click New.
    3. Fill in the fields, as appropriate.

Let’s have a closer look on the business rule form and see the purpose of each field.

business rule in servicenow - servicenowhelpdesk.com

Field on form Illustration
Name

 

Enter the name for your business rule. Try to keep it simple and specific.
Table

 

Select the table from the list provided in the drop down.
Application Application that contains this business rule.
Active Enable of disable your BR using this option.
Advanced This helps to see the advanced version of the form.

 

When to runActionsAdvanced

business rule when to run - servicenowhelpdesk.com

When Select when this business rule should execute display, before, async, or after the database operation is complete. (This appears when advanced is true.)
Order This indicates the sequence in which the BR will be executed. It helps in case where more than one rule is being run on the same condition.
Filter Conditions Condition builder is a no code approach to determine when the business rule should run based on the field values
Role Conditions Select the roles that users who are modifying records in the table must have for this business rule to run.
Insert Used when a record is inserted into the database.
Update Used when a record is update.
Delete Used when a record is deleted from the database.
Query Used when a table is queried

 

Note – Delete and Query operations are available only when advanced checkbox is true.

business rule action - servicenowhelpdesk.com

Set field values Set values for fields in the selected Table using the choice lists:

·       The field

·       The assignment operator:

o   To: An exact value

o   Same as: The value of another field

o   To (dynamic): A value relative to the user configuring the business rule or a user with a specific role

·       The value

 

Add message Enter a message that appears when this your rule is run
Abort action This check box is used to abort the current database transaction.

 

 

business rule advance - servicenowhelpdesk.com

Condition Create a JavaScript conditional statement to specify when the business rule should run.
Script Create a script that runs when the defined condition is true.

 

<strong>Join Runjay Patel</strong>

Thanks for reading this article, i hope you liked it, if that so, do like and subscribe my YouTube channel. You can also join our telegram channel to clear your technical doubt.

 

Types of business rules in ServiceNow

We have four different type of business rules present in our system.

    1. Before
    2. After
    3. Async
    4. Display

Let’s understand each one of them in detail

Before business rule

Before BR as name itself justify works Before a record is saved to the database. Business rules execute after form submission and before the record update in the database. It runs before the database operation, so no extra operations are required.

Before business rule - servicenowhelpdesk.com

As shown in the figure above the user provides an input before BR is executed and then only changes are made to the database.

Scenario – We need to copy the short description from variable present on RITM to the short description of catalog task.

We will start by creating a new Before BR filling all the required fields.

Before business rule scenario - servicenowhelpdesk.com

 

Here is the script to achieve the above-mentioned scenario.

Before business rule scenario - servicenowhelpdesk.com

(function executeRule(current, previous /*null when async*/ ) {
    
    current.short_description = current.request_item.variables.short_description;
    
    // Add your code here


})(current, previous);

 

After business rule

After a record is saved to the database. Business Rules execute after form submission and after the record update in the database.

After business rule - servicenowhelpdesk.com

Scenario – We need to close the task if the respective RITM moves to Closed incomplete.

We will start by creating a new After BR filling all the required fields.

After business rule scenario - servicenowhelpdesk.com

Here is the script to achieve the above-mentioned scenario.

After business rule scenario - servicenowhelpdesk.com

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

    // Add your code here
    var gr = new GlideRecord("sc_task");
    gr.addQuery("request_item", current.request_item);
    gr.addEncodedQuery("stateIN9,-5,1,2,4,7");
    gr.query();
    if (gr.next()) {} else {
        var gr1 = new GlideRecord("sc_req_item");
        gr1.get(current.request_item);
        gr1.state = "10";
        gr1.update();
    }

})(current, previous);

 

Async business rule

Async Business Rules run after records are inserted/modified/queried. Async and after works similar the only difference is async run asynchronously as Scheduled Jobs. Async BR are queued by the scheduler to run as soon as they can be fit in. This allows the current transaction to finish without waiting for the rule and give the control back to user to continue working.

Async Business Rules - servicenowhelpdesk.com

Tip – Use async Business Rules instead of after Business Rules whenever possible.

Scenario: Attachment add to a particular variable in a certain catalog item should get attach to the record as well.

We all are aware that attachment made to a variable in any catalog item is not attached to the record itself and make it somehow difficult to send the same attachment via notification for the respective record. So, to achieve the same we are using Async Business Rule. Now, why async not after BR the answer is attachment might take time to get attach to the record so to make this smooth and without blocking user experience, we will be using this.

We will start by creating a new Async BR filling all the required fields, here we want this BR for a particular catalog item, so we are mentioning the same under filter conditions.

Async Business Rules scenario - servicenowhelpdesk.com

Here is the script to achieve the above-mentioned scenario.

Async Business Rules scenario - servicenowhelpdesk.com

(function executeRule(current, previous /*null when async*/ ) {
   
    var gr = new GlideRecord("sys_attachment");
    gr.addQuery("table_name", "ZZ_YY" + current.getTableName());
    gr.addQuery("table_sys_id", current.sys_id);
    gr.query();
    if (gr.next()) {
        gr.table_name = current.getTableName();
        gr.update();
        new global.VariableUtil().copy(gr.sys_id, current.getTableName(), current.sys_id); 
    }


})(current, previous);

Display business rule

Display Business Rules run after the data is read from the database and before the form is presented back to the user. Display Business Rules execute when a user requests a record form.

Display Business Rules - servicenowhelpdesk.com

Scenario – We need to set certain values on incident form if the logged in user is member of a particular group.

To achieve this use case, we first need to create a Display BR and then call the same in our client script. Please refer to the below attached screenshots.

Display Business Rules - servicenowhelpdesk.com

 

Here is the BR to fulfil our work at server side.

Display Business Rules scenario - servicenowhelpdesk.com

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


    g_scratchpad.fac = (gs.getUser().isMemberOf("a56f4cbfdb252410b9450342f396191c"));
    
})(current, previous);

 

Now, moving onto the client-side scripting to see how this g_scratchpad is called, and our requirement is achieved.

Display Business Rules scenario - servicenowhelpdesk.com

 

function onLoad() {
    //Type appropriate comment here, and begin script below

    var a = g_form.getValue('number');
    if (g_scratchpad.fac == true) {

        var pro = g_scratchpad.property;
        var myArr = pro.split(",");
        var pointer = "0";
        for (var i = 0; i < myArr.length; i++) {
            g_form.removeOption('u_business_service', myArr[i]);
        }
        if (content != '') {
            //alert('script 2');
            g_form.setValue('u_business_service', '10’);
            g_form.setValue('category', '1');
            g_form.setValue('subcategory', '2');
        }
    }

 

Before Query Business rule

Other than the four above mentioned rules we have Before Query rule. It is a type of business rule in ServiceNow that we can use to limit that what all records users can access from a given table. In other words, we can also say that it is used for data segregation on an instance. To understand this more clearly see the scenario mentioned below.

Scenario – We need to restrict the visibility of incident on our instance in such as way that user should only be able to view them if he is a part of the assignment group to which that incident is being assigned or is the caller for that incident.

We will start by creating a new Before BR and selecting the query operation then filling all the required fields.

Before Query Business rule - servicenowhelpdesk.com

Here is the script to achieve the above-mentioned scenario. In this you can see we have used the condition under advanced section to disable this rule if the user is ‘admin’.

Before Query Business rule - servicenowhelpdesk.com

//Condition - gs.getSession().isInteractive() && !gs.hasRole('admin')
 
Script - (function executeRule(current, previous /*null when async*/ ) {

    if (gs.getUser().isMemberOf('2af9bfbc1b04d01081ca85506e4bcb71')) {
        current.addQuery('caller_idDYNAMIC90d1921e5f510100a9ad2572f2b477fe^ORassignment_group=a56f4cbfdb252410b9450342f396191c');
    }

Why should we use Before Query instead of ACL?

With the concept of before query first question which comes to our mind is that why we actual need this when we have ACL for restricting any kind of record in system. The answer is when Query BR restrict the access than user will not see any message at the bottom of page related to access restriction but if the same record is restricted from ACL than message such as “Numbers of rows removed from the list by Security constraints: 20” displayed to user.

So, for smoothening the user experience query BR is preferred over ACL.

 

Order of execution of different Business Rules

Business rule order of execution - servicenowhelpdesk.com

The above image show use how database is being updated once something is entered by user. We can clearly see the execution order of the different business rule and how they work one by one based on the conditions and operation selected.

QUERY > DISPLAY > BEFORE > AFTER

This is in simple words to make you understand the flow. First, the query rule runs to restrict the access of the data being presented to the user. Then the display rule is executed. After that Scripts are configured to execute before the database operation works. And finally, async and after is carried out. 

Best practices for a Business Rule

    1. Prevent recursive business rules – We should avoid using 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.
    2. Enclose your script in functions – We should always enclose our script in functions because when a code is not enclosed inn functions it is available to all server side scripts.
    3. Write specific business rule – Always avoid writing complex rules as they will be difficult to debug.
    4. Know when to run business rule – There should be clarity about when to use Business Rule and specify the same in conditions for running your BR.

Advantage vs disadvantage

Advantage

    • Performance. When running code on the server, it often has a faster load time and   processing time than a client script.
    • Can perform complex database lookups.
    • Can dot-walk many levels, however three levels is often a recommend maximum.

Disadvantage

    • They are not as user friendly as client scripts.

 

FAQ

What is async business rule in servicenow?

Async Business Rules run after records are inserted/modified/queried. Async and after works similar the only difference is async run asynchronously as Scheduled Jobs. Async BR are queued by the scheduler to run as soon as they can be fit in. This allows the current transaction to finish without waiting for the rule and give the control back to user to continue working.

What is before business rule in servicenow?

Before BR as name itself justify works Before a record is saved to the database. Business rules execute after form submission and before the record update in the database. It runs before the database operation, so no extra operations are required.

What is after business rule in servicenow?

After a record is saved to the database. Business Rules execute after form submission and after the record update in the database.

What is display business rule in servicenow?

Display Business Rules run after the data is read from the database and before the form is presented back to the user. Display Business Rules execute when a user requests a record form.

What is before query business rule in servicenow?

Other than the four above mentioned rules we have Before Query rule. It is a type of business rule in ServiceNow that we can use to limit that what all records users can access from a given table. In other words, we can also say that it is used for data segregation on an instance. To understand this more clearly see the scenario mentioned below.

Get Latest Update From Runjay Patel

We don’t spam! Read our privacy policy for more info.

LEAVE A REPLY

Please enter your comment!
Please enter your name here