SNOWYCODE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
How To Call A Script Include From A Business Rule
How To's

How To Call A Script Include From A Business Rule

How To Call A Script Include From A Business Rule

Introduction

A Business Rule serves as server-side Javascript code that executes when specific events occur, such as record display, insertion, update, deletion, or table querying. It plays a pivotal role in controlling the behavior and logic of the system during these events.

A Script Include is a reusable snippet of JavaScript code that can be accessed from any part of the ServiceNow platform. Similar to a Business Rule, it operates on the server-side and utilizes server-side code.

One of the advantages of using a Script Include is that developers can avoid embedding lengthy JavaScript code directly within individual Business Rules. Instead, they can define the code within a Script Include and conveniently call it from the corresponding Business Rule. This approach promotes code organization and reusability, simplifying maintenance and improving overall efficiency in development workflows. By centralizing code logic in a Script Include, developers can streamline their Business Rules and achieve better code management.

If you're looking for how to call a script include from a UI Action instead, check out our guide here.

Real-world Use Case

Let's explore a few practical scenarios where calling a Script Include from a Business Rule proves beneficial:

  • Lengthy Conditions: when dealing with complex conditions, the character limit of 255 in the Business Rule's Condition field can become restrictive. In such cases, where the condition code exceeds this limitation, utilizing a Script Include allows developers to bypass this constraint and incorporate more comprehensive and expressive logic.
  • Loaded on Request: choosing Script Includes over Global Business Rules brings the advantage of loading the code only when explicitly requested. Unlike Global Business Rules, which load with every database action, Script Includes are loaded dynamically when required. This approach promotes better performance and efficiency in the platform.
  • Commonly-used Functions: in scenarios where multiple tables necessitate a Business Rule to perform the same function or logic, employing a single Script Include to manage and control these shared functions proves invaluable. Rather than duplicating the condition code across numerous Business Rules, consolidating them within a Script Include streamlines maintenance and enhances code reusability.

1) Create the Script Include

Before a Script Include can be called by a Business Rule, it must first be created! To create the Script Include, perform the following procedure:

  1. Navigate to System Definition > Script Includes.
  2. Click the New button.

The following fields are available to populate:

  • Name: this is the name of the Script Include.
  • API Name: this field is a combination of the Application Scope and the Name of the script include. It auto-populates when the Name field is filled. Take note of this value, as it is used to call the Script Include from the UI Action.
  • Script: define the JavaScript code that will be utilized by the Script Include. When making the Script Include callable by a Business Rule, ensure that the JavaScript code follows the specified format
 var <ScriptIncName> = Class.create();
<ScriptIncName>.prototype = {
\\ ScriptIncName should match the Name field of the Script Include
    
    initialize: function() {},
    
    <FunctionName>: function() {
    \\ FunctionName can be any value, but take note of whatever it is because the Function Name
        will be referenced in the Business Rule condition/script
		
    
    \\ **Insert function Javascript code here!**


    }, 
    \\ Closes the function
    
    type: '<ScriptIncName>'
    \\ the type should also match the Name field of the Script Include

2) Create the Business Rule

To create the Business Rule, perform the following procedure:

  1. Navigate to System UI > Business Rules.
  2. Click the New button.

The following fields are available to populate:

  • Name: this is the display name of the Business Rule.
  • Table: this field is for selecting the table where the Business Rule should trigger on.
  • Advanced: check this field to reveal more options on the When to run tab. Also reveals the Advanced tab, which is needed to call the Script Include.

When to run tab (with Advanced checked)

  • When: determines the triggering condition for the Business Rule, and specifies when an associated Script Script include should be executed as well. The available options include "Before", "After", "Async", and "Display".
  • Order: set the execution order of the Business Rule. (Lower values execute first) Useful when multiple Business Rules exist on the same table with similar triggering conditions.
  • Insert, Delete, Update, Query: checking these boxes determines what server-side operations this Business Rule triggers on.
  • Filter Conditions: refine the Business Rule trigger condition using a combination of field comparisons and logical operators.

Advanced tab

  • Condition: this field allow a devleoper to provide even further refinement to the Business Rule trigger condition using JavaScript code. When the Business Rule is triggered, it first evaluates the primary triggering conditions on the When to run tab, then evaluates the Condition field script (if any). If all conditions evaluate to true, the Business Rule's associated script is executed. If any condition evaluates to false, the script is skipped. Since the Condition field is limited to 255 characters, it might be necessary to call a Script Include if the instead of writing the code on the Condition field itself. To call a Script Include from the Business Rule's Condition field, the following Javascript code format must be used...
  new <Script-Include-API-Name>.<FunctionName>();

// the "Script-Include-API-Name" should match the API Name field found on the Script Include

// the "FunctionName" should match the name of the name given to the function in the Script
Include's Script field

  • Script (method 1): server-side Javascript code that is executed when the Business rule is triggered. To call a Script Include from the Business Rule's Script field, the following Javascript code format can be used...
(function executeRule(current, previous /*null when async*/) { new TicketContactUtils().createContact(); })(current, previous);

  • Script (method 2): alternatively, the Script field code can also be written as follows...
(function executeRule(current, previous /*null when async*/) { var callScriptInc = new TicketContactUtils(); callScriptInc.createContact(); })(current, previous);

Example Scenario

In the following scenario, the Client uses a custom application with two tables, "Ticket" and "Contact". The Ticket table contains a reference field called "Contact Name", pointing to the Contact table. The Contact table contians a integer field called "Ticket Count", intended to represent how many Tickets were opened with that particular individual as the Contact.

The Client request that, each time a new Ticket is submitted, the Ticket Count field on the corresponding Contact record is incremented by 1.

Script Include settings

Application (Scope): Custom App

Name: TicketIncUtils

API Name: custom_app.TicketIncUtils

Script: see the code below...

 var TicketIncUtils = Class.create();

TicketIncUtils.prototype = {
    initialize: function() {},

    incrementTicketCount: function() {
        var contact = ticket.contact;

        // Check if Contact value is set on the ticket
        if (contact) {
            // Query the Contact table
            var grContact = new GlideRecord('contact_table_name');
            grContact.addQuery('full_name', contact);
            grContact.query();

            // When a matching contact is found, increment the Ticket Count field
            if (grContact.next()) {
                var ticketCount = grContact.getValue('ticket_count') || 0;
                ticketCount += 1;
                grContact.setValue('ticket_count', ticketCount);
                grContact.update();
                gs.info('Ticket Count incremented for contact: ' + contact);
            }
        }
    },

    type: 'TicketIncUtils'
};

Business Rule settings

Application (Scope): Custom App

Name: Increment Ticket Count

Table: Ticket [custom_ticket]

Advanced: true (checked)

When: before

Insert: true (checked)

Update: true (checked)

Script: see the code below...

 (function executeRule(current, previous /*null when async*/) {
	
new custom_app.TicketIncUtils().incrementTicketCount();
	
})(current, previous);

Conclusion

Calling a Business Rule from a UI Action offers an added level of flexibility and capability. By employing a Script Include, developers can bypass the 255 character limit constraints on the Business Rule Condition field, and create more complex and nuanced conditional logic. This means they can define precise criteria for executing their code, resulting in more accurate and efficient operations. Additionally, consolidating the code within a single source, rather than scattering it across multiple Business Rules, simplifies maintenance and ensures consistency. In conclusion, utilizing a UI Action to call a Business Rule, coupled with a Script Include, provides developers with enhanced flexibility and control.

Looking for something else? Check out our other posts below!

Snowycode team
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Read more