Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Business rules
1. Business Rules
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information.
PDF generated at: Fri, 24 Jan 2014 13:34:55 PST
2. Business Rules
Business Rules
Overview
A business rule is a piece of JavaScript configured to run when a record is displayed, inserted, updated, deleted, or
when a table is queried. A business rule can be set to run before or after the database action has occurred. In the case
of a query, the business rule runs before the database operation, so that the data returned to the user is appropriate to
his system privileges (user roles). A typical business rule might execute a script after a user updates an incident or
escalates the priority of a change request. Use a business rule to create new events for email notification and script
actions.
Business Rule Process Flow
Note that business rules apply consistently to records regardless of whether they are accessed through forms, lists, or
web services. This is one major difference between business rules and client scripts, which only apply when editing
through the form.
1
3. Business Rules
2
Business Rules Form
This example is the business rule used for saving updates made to the Change Phase [change_phase] table. The rule
is configured to execute the JavaScript code after an insert or update is made on the Change Phase table.
The Business Rules form provides the following fields.
Field
Input Value
Name
Enter descriptive name for your business rule.
Table
Select the appropriate database table for this business rule.
Order
Type the sequence in which this business rule should run. If there are multiple rules on a particular activity, the rules will run in the
order specified here, from lowest to highest.
Active
Select the check box to enable this business rule and assign it the value true.
When
Select when this business rule should execute: display, before, async (queued), or after the database operation is complete.
Insert
Select the check box to execute the business rule when a record is inserted into the database.
Update
Select the check box to execute the business rule when a record is updated.
Delete
Select the check box to execute the business rule when a record is deleted from the database.
Query
Select the check box to execute the business rule when a table is queried.
Condition Create a statement for a condition under which the business rule should execute. By adding the condition statement to this field, you tell
ServiceNow to evaluate the condition separately and parse the script only if the condition is true. If you decide to include the condition
statement in the script, leave this field blank. To have the instance reevaluate the condition statement a second time before running an
async business rule, add the system property glide.businessrule.async_condition_check.
Script
Create a script that triggers your new event when the condition you define is true.
Related lists on the form view:
Versions
Shows all versions of the business rule. Use this list to compare versions or to revert to a previous version. See Versions.
4. Business Rules
Business Rule Scripting
You create scripts in business rules with JavaScript. The following are the predefined variables that help reference
the system:
• current: The current record being referenced
• previous: The record before any changes were made, available on update and delete operations
• g_scratchpad: Scratchpad object available on display rules, used to pass information to the client to be accessed
from client scripts
• system (or gs): References to GlideSystem functions. See GlideSystem.
Business Rule Variables are Global
System provided variables, such as current, previous, and g_scratchpad are global across all business
rules that run for a transaction. User created variables are also globally scoped by default. This means that if a new
variable is declared in an order 100 business rule, the business rule that runs next at order 200 will also have access
to the variable. This may introduce unexpected behavior.
To prevent such unexpected behavior, it is recommended that you always wrap your code in a function. This protects
your variables from conflicting with system variables or global variables in other business rules not wrapped in a
function. Additionally, variables such as current must be available when a function is invoked in order to be
used.
This is an example of a script that is vulnerable to conflicts with other code. If the variable gr is used in other rules,
the value of the variable may unexpectedly change.
var gr = new GlideRecord('incident');
gr.query();
while (gr.next()) {
//do something
}
When this script is wrapped in a function, the variable is only available within the function and will not conflict with
other functions using a variable named gr.
myFunction();
function myFunction() {
var gr = new GlideRecord('incident');
gr.query();
while (gr.next()) {
//do something
}
}
3
5. Business Rules
Aborting a Database Action in a Business Rule
During a before business rule script you can cancel, or abort, the current database action by using the
current.setAbortAction(true) method. For example, if your business rule is executed with a setting of
before during an Action of Insert, and you have a condition in the script that, when met, calls
current.setAbortAction(true), then the new record stored in current will not be created in the
database.
Global Business Rules
Business rules marked as global in the Table column are loaded and initialized at the beginning of each interaction
between a user and the platform. Global business rules ignore the Condition field. Therefore, unless the script is
wrapped in a function, it will run on every interaction between the user and the platform.
Global business rules that have script wrapped in a function can be called upon by any script running elsewhere.
Client scripts and business rules can reference any function defined in a global business rule. Global business rules
are therefore useful in defining functions to be used repeatedly by a variety of scripts.
Consider using script includes instead of global business rules because script includes are only loaded on request.
Before Versus After Business Rules and current.update()
The function current.update() is unnecessary in a business rule that executes before the database activity.
Use of this function causes double updates and therefore double events. All changes to the current record should be
made in before business rules, which then lets the system update the record. Any after business rules should only
react to the update to do things like create events or update related records (like the incidents related to an updated
change), and therefore should not use current.update().
Display Business Rules
Display rules are processed when a user requests a record form. The data is read from the database, display rules are
executed, and then the form is presented to the user. The current object is available and represents the record
retrieved from the database. Any field changes are temporary since they are not yet submitted to the database. To the
client, the form values appear to be the values from the database; there is no indication that the values were modified
from a display rule. This is a similar concept to calculated fields.
The primary objective of display rules is to utilize a shared scratchpad object, g_scratchpad, which is also sent
to the client as part of the form. This can be useful when you need to build client scripts that require server data that
is not typically part of the record being displayed. In most cases this would require a client script making a call back
to the server. If the data can be determined prior to the form being displayed, it will be more efficient to provide the
data to the client on the initial load. The form scratchpad object is an empty object by default, and only used to store
name:value pairs of data.
To populate the form scratchpad with data from a display rule:
//from display business rule
g_scratchpad.someName = "someValue";
g_scratchpad.anotherName = "anotherValue";
//if you want the client to have access to record fields not being
displayed on the form
g_scratchpad.created_by = current.sys_created_by;
4
6. Business Rules
//these are simple examples, in most cases you'll probably perform some
other queries to test or get data
To access the form scratchpad data from a client script:
//from client script
if (g_scratchpad.someName == "someValue") {
//do something special
}
Determining the Operation Triggering the Business Rule
Sometimes you will script for a business rule that is triggered on more than one action (for example, Insert, Update,
Delete, Query). If you want your business rule script to dynamically branch depending on the action that triggered
the event, you can use the operation() function. See the sample code below:
if( current.operation() == "update" ) {
current.updates ++;
} if( current.operation() == "insert") {
current.updates = 0;
}
Example: Lock Accounts That Don't Meet Role or Active
Requirements
// Lock accounts if bcNetIDStatus != active in LDAP and user does not
// have self-service, itil or admin role
var rls = current.accumulated_roles.toString();
if ( current.u_bcnetidstatus == 'active' &&
( rls.indexOf(',itil,') > 0 ||
rls.indexOf(',admin,') > 0 ||
rls.indexOf(',ess,') > 0 ) ) {
current.locked_out = false;
}
else {
current.locked_out = true;
}
var gr = new GlideRecord ("sys_user");
gr.query();
while(gr.next()) {
gr.update();
gs.print("updating " + gr.getDisplayValue());
}
5
7. Business Rules
6
Enhancements
Aspen
In the Aspen release, two Async Delete Warning client scripts use showFieldMsg()
addInfoMessage() when warning against using Current in an async business rule.
instead of
Business Rules in the Base System
Overview
The table on this page includes a description of each business rule included in the out-of-box ServiceNow system
and a short description of what it it does. Depending on the version of ServiceNow you are using, some business
rules on this list might not be present or might operate in a slightly different way. This list includes business rules
installed by plugins that are installed by default, but does not include business rules that come with optional plugins.
Business Rules
Business Rules
Table
When
Description
Add Approver If Process Guide running
Approval
[sysapproval_approver]
before
This business rule adds the approvals if a
process guide is running.
Adjust install counts for licenses
Software [cmdb_ci_spkg]
after
Updates the install counts on the Software
table for all licenses with non-discoverable
keys.
Affected ci notifications
Task [task]
async
Notifies subscribers when CIs are affected by
an incident.
Affected cost center notifications
Task [task]
async
Notifies cost center subscribers when CIs
related to the cost center are affected by an
incident.
Affected group notifications
Task [task]
async
Notifies group subscribers when CIs assigned
to the group are affected by an incident.
Affected location notifications
Task [task]
async
Notifies location subscribers when CIs in a
specific location are affected by an incident.
Allow either workflow or delivery plan
Catalog Item [sc_cat_item]
before
If a workflow is specified, the Delivery Plan
field will be emptied, because both cannot be
used.
approval events
Approval
[sysapproval_approver]
after
Generates all of the events in the approval
process. Important for driving email
notifications based on approvals.
approval query
Approval
[sysapproval_approver]
before
approver changes
Asset Adjust License Count
Software License
[ast_license_base]
after
Updates the install counts on the Software
License table for all licenses with
non-discoverable keys.
Asset Adjust Used License Count
Software License Instance
[ast_license_instance]
after
Updates the install counts on the Software
License Instance table for all licenses with
non-discoverable keys.
8. Business Rules in the Base System
7
Assign from Stock
Requested Item [sc_req_item]
after
If a requested item's Configuration Item is
changed to an existing CI record, the business
rule will update the CI record to indicate that
it is being assigned to the requester.
Attach Delivery Plan
Change Request
[change_request]
after
If a change request does not have a delivery
plan attached, this business rule will attach a
delivery plan.
Attachment events
Attachments [sys_attachment]
after
Generates events based on an attachment
being attached to a record.
Audit Relationship Changes
Group Relationships
[cmdb_rel_group]
after
Audits the group relationships in the CMDB.
Audit Relationship Changes
People Relationships
[cmdb_rel_person]
after
Audits the people relationships in the CMDB.
Audit Relationship Changes
CI Relationships
[cmdb_rel_ci]
after
Audits the CI relationships in the CMDB.
Auto Close On Approval
Change Task [change_task]
before
Auto-closes the current change task if it is
marked as approved as part of an existing
delivery plan.
Auto Close On Approval
Catalog Task [sc_task]
before
Auto-closes the current catalog task if it is
marked as approved as part of an existing
delivery plan.
Auto set workflow from workflow version Workflow Context
[wf_context]
before
Enforces that the Workflow Version's
Workflow field matches the Workflow
Context's Workflow field.
Auto start on context
Workflow Context
[wf_context]
after
If the auto_start flag is true on a workflow
context, this business rule drives the auto
start.
automatic renumber
Task [task]
before
Enforces task number uniqueness.
automation synchronizer
Scheduled Job [sysauto]
after
Synchronizes the scheduled jobs.
Boolean Protection
Dictionary [sys_dictionary]
before
Prevents users from changing boolean fields
to non-boolean fields.
Build Connection URL
Data Source [sys_data_source] before
Generates the connection URL for the data
source.
Calc SLAs on Display
Task [task]
display
Calculates the stage and elapsed time of an
SLA affected by an incident when the
incident form displays.
Calculate Article Rating
Knowledge Feedback
[kb_feedback]
async
Calculates the article rating based on the
aggregates all of the ratings cast.
Calculate expires in days
X.509 Certificate
[sys_certificate]
before
Calculates the amount of time left before the
X.509 Certificate expires.
Calculate Request Item Due Date
Requested Item
[sc_request_item]
before
Calculates the due date of the request item by
adding the delivery time to the time that the
record was assigned.
Calculate Total Delivery Time
Execution Plan Task
[sc_cat_item_delivery_task]
before
Calculates the total delivery time for an
execution plan.
calculatePriority
Global [global]
Calculates the priority level used for priority
fields.
9. Business Rules in the Base System
8
Cancel Workflows Upon Cancellation
Task [task]
after
If the task State changes to Closed
Incomplete (4), cancel related workflows so
that tasks do not remain active.
Cascade Request Approval to Request
Item
Request [sc_request]
after
Cascades any changes made to the approval
field of a service catalog request to the
requested items attached to that request.
certificate events
X.509 Certificate
[sys_certificate]
before
Generates events based on changes to the
X.509 Certificates.
change events
Change Request
[change_request]
before
Generates events related to Change Requests.
Change Own Profile
User [sys_user]
before
If a user changes their Time, Date, or
Timezone formatting in their user profile, this
business rule updates their current session to
match the new settings.
Change Phase Events
Change Phase [change_phase]
after
Generates the events related to Change
Phases after the Change Phase is loaded.
Change Phase Events Before
Change Phase [change_phase]
before
Generates the events related to Change
Phases before the Change Phase is loaded.
Change state on closed Insert
Incident [incident]
before
Updates the state field in the Task table to
match the incident_state field when the
incident is closed.
change reopen
Change Request
[change_request]
before
If the state is changed on a Change Request
that was previously closed, this business rule
returns the Request to active.
Check max_length
Variables [var_dictionary]
before
Enforces a maximum length on variables of
40 characters.
Choice Events
Choices [sys_choice]
after
Generates the events related to Choices
before the Choice is loaded.
Choices unload
Choices [sys_choice]
after
Unloads choices.
Clear JDBC table name
Data Source [sys_data_source] after
If the data source's type is JDBC, the table
value is cleared.
Close Parent if Required
Requested Item
[sc_request_item]
after
If a requested item is either cancelled or
delivered, the business rule checks to see if
there are other active requested items
attached to the parent request. If there are
none, then the parent request is updated with
the same state.
Close Tasks Due to Cancellations
Requested Item
[sc_request_item]
after
If a requested item is cancelled, all of the
tasks created by that requested item are
closed.
Close Ticket
Change Task [change_task]
before
If the Change Task is marked either as
complete or cancelled, the business rule
closes the ticket and populates fields related
to closure (e.g. Work End).
Close Ticket
Catalog Task [sc_task]
before
If the Catalog Task is marked either as
complete or cancelled, the business rule
closes the ticket and populates fields related
to closure (e.g. Work End).
cmdb synch event
Configuration Item [cmdb_ci]
after
Generates a roll-up event every time a CI is
changed.
10. Business Rules in the Base System
9
cmdbCIChildren
Global [global]
cmdb_rel_ci synch event
CI Relationship [cmdb_rel_ci]
A script which lists all of the children of a
configuration item.
after
cmdb_rel_suggest_relationshipGetChoices Global [global]
Generates a roll-up event every time a CI is
changed.
A script which lists all of the choices for
suggested relationships.
Company Projection
Incident [incident]
before
Populates the company field with the caller's
company field if an incident has a caller listed
but no company listed.
Condition Field validation
Condition Checks
[cmn_condition_check]
before
Enforces the requirement that the condition
field is a reference to cmn_condition_checker
Contain Changes
Contained Role
[sys_user_role_contains]
after
Applies changes in the Contained Role table
to the role manager.
Contract Instance
Lease Instance
[ast_contract_instance]
before
Populates the Contract Instance with
information from the Contract record, and
from the CI record.
Convert to Reference Currency
Price [fx_price]
before
Converts the price to a reference currency.
Create activity
Workflow Instance
[wf_workflow_instance]
before
If there is no activity in the instance of a
workflow, this business rule generates the
next activity in the workflow instance based
on the workflow itself.
Create default conditions
Workflow Activity
[wf_activity]
after
Generates default conditions for each
workflow activity if the activity has no
parent.
Create External Dependencies
Request [sc_request]
after
Generates external dependencies.
Create Flip Side
Suggested Relationship
[cmdb_rel_type_suggest]
after
Generates the mirror relationship for the
current relationship.
Create Inventory Item
Requested Item [sc_req_item]
after
When a requested item's stage reaches
Complete, it generates a CMDB record for
the requested item.
Create module table
Module [sys_app_module]
after
When a module is inserted, it checks if there
is a table already tied to the module. If not, it
creates a table.
Create or Remove Text Index
Dictionary Entry
[sys_dictionary]
before
If the attribute text_index is changed, the
business rule either requests a text index or
disposes of the existing text index, as
appropriate. Note that the business rule
Create Text Index actually performs the text
index creation.
Create Request Item Child Tasks
Requested Item [sc_req_item]
after
When a requested item is created, this
business rule generates the execution plan
tasks based on the item's execution plan.
Create Text Index
Text Search Tables [ts_table]
after
If text_index is set to true in the System
Dictionary, this business rule will index the
text within all of the records for use in the
global text search.
CreateElement
Dictionary Entry
[sys_dictionary]
after
Creates an Element in the Dictionary.
11. Business Rules in the Base System
10
CTI Processing
Global [global]
Parses the payload from a URL generated by
CTI. For more information, see Computer
Telephony Integration (CTI).
Currency Filter
Global [global]
Filters the display of currencies.
Date Globals
Global [global]
Establishes the javascript functions now()
nowDateTime() and lastweek()
Delegates
Delegate [sys_user_delegate]
before
Prevents users from assigning other user
delegates unless they are an administrator.
Delete databases on change
Round Robin Definition
[jrobin_definition]
after
If a Round Robin Definition changes, this
business rule deletes any databases that were
using it.
Delete databases on change
Round Robin Archive
[jrobin_archive]
after
If a Round Robin Archive changes, this
business rule deletes any databases that were
using it.
Delete Impacted Services
Task [task]
after
Deletes affected services when the task is
deleted.
Delete parent workflow
Workflow Version
[wf_workflow_version]
after
If the last remaining workflow version of a
parent workflow is deleted, this business rule
deletes the parent workflow.
Delete software license instance
Software Instance
[cmdb_software_instance]
after
If the software instance is deleted from the
CMDB table, this business rule deletes the
software license from the asset table.
Delete table column
Dictionary Entry
[sys_dictionary]
after
Deletes a table column.
Delete Tasks for Deleted Requested Item
Requested Item [sc_req_item]
before
If requested items are deleted, any tasks
generated by the requested items are deleted
as well. It also rebalances the request's price
to reflect the change.
Delete Text Index
Dictionary Entry
[sys_dictionary]
after
Queues the text index for deletion.
deleteAllRecords
Global [global]
Dictionary change
Dictionary Entry
[sys_dictionary]
after
Flushes the system's cache after a change in
the dictionary.
Dictionary change length
Dictionary Entry
[sys_dictionary]
after
Changes the maximum length of fields.
Dictionary change rationally
Dictionary Entry
[sys_dictionary]
before
Prevents dictionary field truncation.
dynamicUserCreation
Global [global]
ECC Queue - mark outputs processed
Queue [ecc_queue]
after
Marks outputs of the ECC Queue as
"processed."
ECC Queue - mark outputs state
Queue [ecc_queue]
before
Marks the state of the outputs of the ECC
Queue.
ECC Queue Reader
Queue [ecc_queue]
async
Reads the input of the ECC Queue.
Email Style Verification
Stationery
[sysevent_email_style]
before
Checks the style field of an email to ensure
that ${body} appears in the style field.
A function for deleting all records from a
particular table.
A function for creating a user from a string
value. It splits the value at the space, and then
properly capitalizes the first and last names.
12. Business Rules in the Base System
11
emailsToUsers
Global [global]
This function converts an email address to
user names. If
glide.ui.activity.email.use_display is set to
true, this function is called in the activity
headers of emails.
Ensure unique target field
Field Map
[sys_transform_entry]
before
Enforces target field uniqueness when
building a transform map.
Ensure Valid Schedule
Schedule Item [sys_trigger]
before
Validates the schedule for the schedule item.
Expand Roles
User Role [sys_user_has_role]
after
Updates the roles for a user on change.
Field Deletion Cleanup
Dictionary Entry
[sys_dictionary]
after
When a field is deleted from the dictionary,
this business rule deletes all onChange()
Client Scripts and UI Policy Actions that
applied to the field.
Flush Form Cache
Client Script
[sys_script_client]
after
Flushes the cache every time a client script is
changed or updated.
Flush Form Cache
UI Policy [sys_ui_policy]
after
Flushes the cache every time a UI Policy is
changed or updated.
Flush Form Cache
UI Policy Action
[sys_ui_policy_action]
after
Flushes the cache every time a UI Policy
Action is changed or updated.
Flush RealForm Cache
Module [sys_app_module]
after
Flushes the realform cache every time a
module is changed or updated.
Flush RealForm Cache
Application
[sys_app_application]
after
Flushes the realform cache every time an
application is changed or updated.
Flush RealForm Cache
UI View [sys_ui_view]
after
Flushes the realform cache every time a UI
View is changed or updated.
Flush the activity definition cache
Workflow Activity Definition
[wf_activity_definition]
before
Flushes the activity definition cache every
time an activity definition is changed or
updated.
Flush Variables Cache
Variables [var_dictionary]
after
Flushes the cache every time a variable is
changed or updated.
Force Priority Calc
Incident [incident]
before
Forces calculation of priority based on impact
and urgency using the calculatePriority()
function in the calculatePriority business rule.
Format last run datetime
Data Source [sys_data_source] before
Formats the last_run_datetime field in the
data source.
genChangePlanURL
Global [global]
A function for generating a URL for the
change plan.
Generate activity sequences
Workflow Version
[wf_workflow_version]
before
Generates a list of sys_ids for each path
through the workflow, which is used to check
if an activity has been skipped.
Generate prices
Price [fx_price]
after
Generates the price after a change.
Generic ECC Queue Update
Queue [ecc_queue]
after
Updates records on the ECC Queue.
Geocode Address
Map Page [cmn_map_page]
before
Converts an address to latitude and longitude
coordinates.
Get Attributes
X.509 Certificate
[sys_certificate]
before
Parses the certificate to get the attributes.
Get Display Value
Global [global]
A function for getting the display value of a
sys id.
13. Business Rules in the Base System
12
Get Number
Global [global]
Gets the next number in a series of numbers.
Used for Number Maintenance.
getDefaultDeliveryPlan
Global [global]
Gets the default execution plan.
GetGroupFilter
Global [global]
Performs a lookup on the group type display
values and returns a query condition that will
query on the group type sys_id values.
getGroupMembersM2M
Gets the list of users who are members of a
particular group.
GetIDValue
Global [global]
Gets the sys_id and the display values for a
given table.
getLDAPSources
Global [global]
Gets the list of LDAP Sources.
getMYApprovals
Global [global]
Gets the list of the current user's approvals
and assignments.
getNextObjNumberPadded
Global [global]
Gets the next number in a series with the
padding specified by the Number
Maintenance settings.
getNodesInSameCluster
Global [global]
Gets the nodes in the same cluster.
getQuestionOrder
Question Choices
[question_choice]
GetReasonForChange
Global [global]
Displays the reason for a change.
getRelatedRecords
Global [global]
Displays records related to a record.
getResourcesInSameCluster
Global [global]
Looks up other nodes in the same cluster.
getRoledUsers
Global [global]
Returns an array of sys_ids of users that have
at least one role. Has optional parameters to
allow the exclusion of certain roles, or
inclusion of only certain particular roles.
Optional: queryCondition 'IN' or 'NOT IN' to
include or exclude. Optional: roleList - a
comma separated list of role names.
getTasksWithSameParentM2M
Global [global]
Gets the list of tasks with the same parent.
getUserDashboards
Global [global]
Gets the list of dashboards that belong to a
user.
getUserHomepages
Global [global]
Gets the list of homepages that belong to a
user.
get_lat_long
Location [cmn_location]
async
Gets the latitude and longitude of an address
for a location record.
get_lat_long
Company [core_company]
async
Gets the latitude and longitude of an address
for a company record.
global events
Global [global]
Generates events that apply globally.
Google Map API
Global [global]
Generates the API used to communicate with
Google Maps.
Group Member Add
Group Member
[sys_user_grmember]
after
When a user is added to a group, this business
rule adds all of the roles that group members
should inherit.
Group Member Delete
Group Member
[sys_user_grmember]
after
When a user is removed from a group, this
business rule removes all of the roles that
group members had inherited.
before_display
Gets the order for question choices.
14. Business Rules in the Base System
13
group query
Group [sys_user_group]
after
Checks to see if a user is a member of a
group.
Group Role Changed
Group Role
[sys_group_has_role]
after
If a role is either marked or unmarked
Inherited, this business rule applies the role to
all group members or removes the role from
all group members.
Group Role Deleted
Group Role
[sys_group_has_role]
after
If a role is deleted, this business rule deletes
the role from members and from child
groups.
groups, banners
Global [global]
incident autoclose
Incident [incident]
after
Automatically closes incidents that are
resolved and have not been updated, based on
the glide.ui.autoclose.time property.
Incident Create Knowledge
Incident [incident]
after
Creates a knowledge article from the incident
and formats the output if the "Create
Knowledge" checkbox is selected.
incident events
Incident [incident]
after
Generates the events related to incident.
incident functions
Global [global]
Prevents recursive company loops.
Defines three useful functions for Incidents:
•
•
•
incidentGetViewName()
incidentGetCaller()
sys_userGetEmailAddress
incident query
Incident [incident]
before
Queries the incident if the user has the itil
role. Enables ESS users on the watch list to
see Incidents.
incident reopen
Incident [incident]
before
Reopens an incident if the state changes to
anything other than closed.
Incident Time Worked
Incident [incident]
after
Updates the Time Worked field every time
the incident record is worked on.
Insert Change Phases
Change Request
[change_request]
after
Generates the change phases based on the
change request.
insert_change
Change Request
[change_request]
before
Generates a new number for a new Change
Request (see Number Maintenance).
insert_change
Incident [incident]
before
Generates a new number for a new Incident
(see Number Maintenance).
insert_incident
Incident [incident]
before
Creates a new incident and increments the
identification number sequentially, using the
configured prefix and padding.
insert_lease
Lease [ast_lease]
before
Generates a new number for a new Lease (see
Number Maintenance).
insert_problem
Problem [problem]
before
Generates a new number for a new Problem
(see Number Maintenance).
insert_service
Service Contract [ast_service]
before
Generates a new number for a new Service
Contract (see Number Maintenance).
insert_warranty
Warranty [ast_warranty]
before
Generates a new number for a new Warranty
(see Number Maintenance).
isAdvancedUI
Global [global]
This function checks whether the value of the
property glide.ui.advanced. If this property
is true, it enable the advanced UI.
15. Business Rules in the Base System
14
itil appointment
Appointment
[itil_appointment]
after
Creates events for updates or inserts on the
Appointment table.
KB Events Article
KB Submission
[kb_submission]
after
Creates events for an article being created
from a submission.
KB Events Duplicate
KB Submission
[kb_submission]
after
Creates events for an article being closed as a
duplicate.
KB Events Invalid
KB Submission
[kb_submission]
after
Creates events for an article being closed for
being invalid.
KB Events New Submission
KB Submission
[kb_submission]
after
Creates events for an article being submitted.
Kill User Session
Logged in User
[v_user_session]
before
Kills a user session when a Logged in User
record is deleted.
Label Auto Assignment
Label auto [label_auto]
before
Assigns labels automatically.
Kill User Session
Logged in User
[v_user_session]
before
Kills a user session when a Logged in User
record is deleted.
load ajax globals
AJAX Script [sys_script_ajax]
after
Reloads AJAX global scripts when they are
changed.
load globals
Business Rule [sys_script]
after
Reloads global business rules when they are
changed.
Location - generate full name
Location [cmn_location]
after
Calls HeirarchicalReference to generate the
full location name.
Lock Out Inactive Users
User [sys_user]
after
If a user record is set to active = false, this
business rule sets locked_out = true.
Lock Out User
User [sys_user]
after
If locked_out = true, it kills any sessions
initiated by the locked out user.
mark closed
Task [task]
before
If the state changes to Closed, Active is set to
false.
Mark Request Closed
Request [sc_request]
before
If a request moves to closed, this business
rule sets the end-time values and marks the
request as inactive.
Mark Submission Closed
KB Submission
[kb_submission]
before
If the status is set to closed, the active flag is
set to false.
mark_closed
Incident [incident]
before
If the incident state is set to Closed, the
incident is set to Inactive, the closed_by and
closed time values are set, and the duration is
calculated.
mark_closed
Change Request
[change_request]
before
If the change state is set to closed, the active
flag is set to false.
mark_closed
Problem [problem]
before
If the problem is set to closed, the active flag
is set to false, and the closed_by and
closed_at values are set.
Metric definition
CI Metric [cmdb_metric]
after
Defines the metrics. See Metric Definition
Plugin.
Metric population
CI Metric [cmdb_metric]
after
Populates the defined metrics. See Metric
Definition Plugin.
metrics events
Task [task]
before
Creates events related to Metric Definitions.
metrics instance - set display value
Metric [metric_instance]
before
Sets the display value for the metric field.
16. Business Rules in the Base System
15
Monitor - Process NMAP IP Range Events Event [ecc_event]
before
Processes NMAP IP range events.
Monitor - SSH Processor
Queue [ecc_queue]
after
Processes SSH in the ECC Queue.
Moot Approvals Upon Cancellation
Task [task]
after
Marks group and individual approvals as
inactive if a task is cancelled.
No Duplicates
Dictionary Entry
[sys_dictionary]
before
Enforces dictionary entry uniqueness.
Notification Device View Filter
Global [global]
Outage Calculations
Outage [cmdb_ci_outage]
Package Adjust Install Count
Software License Instance
after
[ast_license_package_instance]
Adjusts the install count of software.
Pad Numbers
Sys number [sys_number]
async
When the maximum digit changes, this
business rule adds padding to the number.
Parent Bumper
Plan Sequencing
[sc_cat_item_dt_mtom]
after
Updates the delivery plan based on the
delivery plan tasks.
Parent changes
Group [sys_user_group]
after
If a group changes parent groups, this
business rule applies the appropriate roles.
Post Outage to News
Business Service
[cmdb_ci_service]
after
If an outage occurs, it creates a new news
article.
Prevent Creation of 2nd Default
Update Set [sys_update_set]
Before
Prevents users from creating an update set
called "Default" when there is an existing
update set of that name.
Prevent Recursion
Table class [sys_db_object]
before
Prevents recursion when a table's super_class
changes.
Prevent Recursion
Category [sc_category]
before
Prevents recursion when a category's parent
changes.
Prevent Recursion
Group [sys_user_group]
before
Prevents recursion when a group's parent
changes.
Prevent removal/update of primary CI
Task [task_ci]
before
To keep information synchronized, this
business rule prevents removal of an affected
CI if it is for the CI on the task form.
Prevent Update of Default
Update Set [sys_update_set]
Before
Prevents users from renaming or deleting the
Default update set record.
problem events
Problem [problem]
after
Generates the events related to problems.
problem_reopen
Problem [problem]
before
If a problem moves from a closed state to
another state, this business rule marks the
active flag as true.
Process Get Stock Quote
Queue [ecc_queue]
before
Gets current stock prices.
Process Rejection
Change Task [change_task]
after
Responds to a rejected change task.
Process Rejection
Catalog Task [sc_task]
after
Responds to a rejected catalog task.
Process SLAs
Task [task]
async
Looks for new SLAs to start, then processes
active SLAs for this task.
Process Web Service Automap
Queue [ecc_queue]
before
Processes web services using the automap.
Properties change
System Property
[sys_properties]
after
Flushes the cache and applies any changes to
properties.
Filters notification devices based on role.
before
If beginning and end times are present,
calculates the outage duration.
17. Business Rules in the Base System
16
Properties track css
System Property
[sys_properties]
after
Updates CSS version.
reassignment counter
Incident [incident]
before
Increments the Reassignment Count field
each time a task is reassigned.
Reference allow invalid
Variables [var_dictionary]
after
Allows invalid variables.
Reference Protection
Dictionary Entry
[sys_dictionary]
before
Prevents setting a reference type field without
referencing a table.
Reject Parent
Catalog Task [sc_task]
after
If a catalog task is rejected, the parent request
is rejected as well.
Reload import sets
Import Set [sys_import_set]
after
Sets all import sets to pending, so that they
will be reloaded.
Reminder Runner
Reminder [reminder]
after
Generates a reminder.
Reminder Runner
Reminder [reminder]
after
Generates a reminder.
Report Helpers
Global [global]
Defines a series of functions to help with
generating reports:
•
•
•
•
getGroupMembers - Returns an array of
all the users that are in any of the groups
specified.
getGroupMembersGivenGroupName Add members of a specified group into an
array.
getGroupMembersGivenGroupID Add members of a specified group into an
array.
getAllMembersOfMyGroups - Gets an
array of all users that belong to the same
groups that the current user belongs to.
Report Title
Report [sys_report]
before
Adds a report title if none is specified.
request closure
Request [sc_request]
after
If a catalog request is closed, this business
rule closes child requests, requested items,
and cancels approvals.
Request item handling
Workflow Version
[wf_workflow_version]
before
Sets up the workflow version to handle
requested items correctly.
Request reopened
Request [sc_request]
before
If the user changed the state to be not closed,
this business rule reopens the request by
setting it active.
Reset Binding
Change Task [change_task]
before
Resets the state binding on a change task
when it is re-entered.
Reset Binding
Catalog Task [sc_task]
before
Resets the state binding on a catalog task
when it is re-entered.
sc req item events
Requested Item [sc_req_item]
after
Generates the events for requested items.
sc req events
Request [sc_request]
after
Generates the events for requests.
Schedule Item validate
Schedule Entry
[cmn_schedule_span]
after
Validates the schedule item.
sc_req_item_stageGetChoices
Global [global]
sc_task_events
Catalog Task [sc_task]
Search Group Delete
Text Search Groups [ts_group] before
Returns the stages for a Request Item as a
choice list.
after
Generates the events for catalog tasks.
Deletes a search group.
18. Business Rules in the Base System
17
Search Table Info for Group
Text Search Tables [ts_table]
after
Generates table information for the search
groups.
Search Table Preference
Text Search Tables [ts_table]
after
Applies the users' preferences on search
groups.
Set Active Flag
Requested Item [sc_req_item]
before
If a requested item is set to complete, this
unmarks the active flag and cancels any
currently running workflows.
Set default start
Wizard Panel [expert_panel]
after
Sets a panel to be the default first panel.
Set Details
Suggested Relationship
[cmdb_rel_type_suggest]
before
Sets the details of the current relationship.
Set Flag
Knowledge [kb_knowledge]
before
If a knowledge article is flagged, this
business rule makes a note of the fact on the
feedback table.
Set Flagged Status
Knowledge Feedback
[kb_feedback]
after
Ensures that the flag on the knowledge article
matches the flag on the feedback table.
Set from field
Workflow Transition
[wf_transition]
before
Sets activity condition from a field.
Set Inbox
Email [sys_email]
before
Sets a new email inbox.
Set info from activity definition
Workflow Activity
[wf_activity]
before
Sets the default width, height, and is_parent
flag on an activity.
Set javascript class name
Workflow Activity
[wf_activity]
before
Enforces propercase for Javascript class name
in the activity.
Set label and help
Variables [var_dictionary]
after
Deletes related entries, and updates the
related documentation entries.
Set Parent
Change Task [change_task]
before
Sets the Change Request as the Change
Task's parent.
set pretty name
Field Setter
[expert_panel_t_fields]
before
Gives a pretty name to a field.
Set Request State
Request [sc_request]
before
Sets the state of the catalog request.
Set Resolved Checkbox
Knowledge Feedback
[kb_feedback]
before
If a knowledge article is unflagged, the
business rule marks the resolved checkbox.
Set selected color
Graph Line
[jrobin_graph_line]
before
Sets the graph line according to the color
picker.
Set State
Queue [ecc_queue]
before
Sets the state of queue items after processing.
Set System Flag
User Preference
[sys_user_preference]
before
Sets the system flag on null users or global
users.
Set wait_for to workflow
Group Approval
[sysapproval_group]
before
Sets the wait_for field to be 'workflow' if this
approval was created by a workflow activity
Set workflow scheduler
Workflow Schedule
[wf_workflow_schedule]
before
Sets the workflow scheduler.
SNC - Create user approvals for group
Group Approval
[sysapproval_group]
before
Creates user approvals for approvals assigned
to a group.
SNC - Database View Documentation
Database View [sys_db_view]
after
Creates a language entry for database views.
SNC - Delete user approvals for group
Group approval
[sysapproval_group]
after
Deletes the user approvals for a group when
the group is deleted.
SNC - ITIL - Close Related
Problem [problem]
after
Closes any incidents that are related to the
current problem.
19. Business Rules in the Base System
18
SNC - ITIL - Close Related
Change Request
[change_request]
after
Find related problems for a change_request
and close them.
SNC - ITIL - Close Related
Global [global]
SNC - ITIL - Close Related
Incident [incident]
after
Finds related incidents for the current
incident and closes them.
SNC - Match state to approval
Group approval
[sysapproval_group]
before
Makes sure the state matches the approval
value.
SNC - Moot user approval
Group approval
[sysapproval_group]
after
Set all of the pending user approvals for this
group approval to Not Required.
SNC - Run parent workflows
Task [task]
after
Restarts a running parent workflow, when the
current task is completed.
SNC - Run parent workflows
Approval
[sysapproval_approver]
after
Run any workflows so the approval's state
can be checked.
SNC - Run parent workflows
Group Approval
[sysapproval_group]
after
Run any workflows so the group approval's
state can be checked.
SNC Approval - Reset conditions
Change Request
[change_request]
before
The reset conditions for approvals. Note: this
business rule is inactive by default. The
business rule provides instructions for
activating the business rule within the
comments of the script.
SNC Baseline Filter
Global [global]
A function to get a filter for the baseline.
SNC Baseline Globals
Global [global]
A function to check proposed changes
globally.
SNC Create Baseline
CMDB Baseline
[cmdb_baseline]
after
Schedules a create baseline scheduled job.
SNC Create Unique Index
Dictionary Entry
[sys_dictionary]
after
Creates a unique index entry.
SNC Dictionary
Global [global]
Find related tasks for the current task and
close them.
Defines two functions for getting values from
the dictionary:
•
•
doesEntryFloat
getDictionaryEntry
SNC Global Listener
Global [global]
Gets control for each field that has an
attribute of "listen". If a change has not been
authorized then a problem record will be cut
for the change.
SNC Invalidate LDAP
Import Export Map
[sys_impex_map]
after
Flushes the cache after an update of the
import/export map.
SNC Invalidate LDAP1
Field Map [sys_impex_entry]
after
Flushes the cache after an update of the
import/export map.
SNC label query
Label [label]
before
Checks user to generate user-specific labels.
SNC ManyToMany Create
Many to Many Definition
[sys_m2m]
before
Creates a many-to-many table.
SNC Release Complete
Release [release_project]
async
Completes a release by closing all related
problems and posting all of the records to
Definitive Software Library.
SNC Release Delete Phases
Release [release_project]
async
Deletes release phases upon completion.
20. Business Rules in the Base System
SNC Release feature
19
Feature [release_feature]
before
Verifies that:
•
•
•
The feature is part of a product and is part
of a release
The release is part of a product
The release and the feature are part of the
same product
SNC Release feature events
Feature [release_feature]
before
Creates a release feature.
SNC Release Insert Phases
Release [release_project]
async
Creates a release phases based on the release.
SNC Release phase
Release Phase [release_phase]
before
Sets the start and end dates based on the
approval.
SNC Release phase - new
Release Phase [release_phase]
before
Links new release phases.
SNC Release phase events
Release Phase [release_phase]
after
Generates the events for release phases.
SNC Release project - feature
Release [release_project]
after
Applies changes in state to child features.
SNC Release Project - New
Release [release_project]
before
Set the release manager equal to the related
product manager.
SNC Release project complete
Release [release_project]
before
If state changes to complete, then mark
release inactive.
SNC Release project events
Release [release_project]
after
Generates the events for releases.
SNC Release task events
Feature Task [release_task]
after
Generates the events for feature tasks.
SNC Report Clean
Report [sys_report]
after
Cleans superfluous reports.
SNC Template Group Qual
Global [global]
SNC Template Query
Template [sys_template]
before
Filters the templates by user, so that users
will only see templates that are available for
them wherever they are in the system.
Deactivating the SNC Template Query
business rule has the effect of allowing users
to see all templates. The Aspen release
includes a new version of the Read ACL for
sys_template and the template query business
rules to ensure that users can see applicable
templates.
SNC Transaction History
Sys trend [sys_trend]
after
Send transaction history records back to /hi
periodically.
SOAPClient
Queue [ecc_queue]
before
Parses SOAP packages.
Stamp Approvals
Task [task]
before
Marks approvals with a timestamp when the
approval status changes.
Start Change Tasks
Change Request
[change_request]
after
Starts the change tasks when the change is
approved.
Start Peer Tasks (change_task)
Change Task [change_task]
after
When a change task ends, this business rule
starts the next change task.
Start Tasks
Requested Item [sc_req_item]
after
When a requested item is approved, this
begins the first catalog task.
Start Workflow
Requested Item [sc_req_item]
before
When a requested item is approved, this
initializes the workflow, and puts the
variables from the requested item into the
workflow if the names match.
String class extensions
Global [global]
A function to gets a reference qualifier for a
template group.
21. Business Rules in the Base System
20
String functions
Global [global]
Removes the white space in strings.
Survey Reference Responses
Survey Responses
[survey_response]
before
Gets display value for survey responses.
Sys language updates
Field Label
[sys_documentation]
after
Flushes the cache when the field labels are
updated.
Sync CI answers with CI modules
sys_wizard_answer
after
Along with the Sync Interceptor Answers
with CI Modules business rule, synchronizes
roles and active fields for table-specific
CMDB modules with their corresponding
cmdb_ci.do interceptor answers. This
behavior is controlled by a new property,
glide.ecmdb.synch_modules_with_interceptor,
which is set to true by default.
Sync CI with Affected CIs
Task [task]
after
Copies the CI on the form to the Affected CIs
related list. To keep information
synchronized, if the CI on the form changes,
the old one is removed from the related list
and the new one is added.
Sync Interceptor Answers with CI
Modules
sys_app_module
after
Along with the Sync CI answers with CI
modules business rule, synchronizes roles and
active fields for table-specific CMDB
modules with their corresponding cmdb_ci.do
interceptor answers. This behavior is
controlled by a new property,
glide.ecmdb.synch_modules_with_interceptor,
which is set to true by default.
System Deploy Approved
Change Request
[change_request]
async
Begins a ServiceNow deployment when
approved.
System Deploy Confirm
Queue [ecc_queue]
async
Parses a system deployment confirmation.
System Deploy Create
Queue [ecc_queue]
async
System Deploy Request
Queue [ecc_queue]
async
Requests a new instance from /hi.
system property events
System Property
[sys_properties]
after
Generates the events for properties.
system property schedulers
System Property
[sys_properties]
after
Restarts the scheduler if glide.sys.schedulers
is modified.
System Update Confirm
Queue [ecc_queue]
async
Confirms a system update.
sys_dictionary
Global [global]
task closer
Task [task]
before
Sets the task state to Closed if the task has
been closed.
task events
Task [task]
after
Generates the events for a task when an
approval is rejected or approved.
task reopener
Task [task]
before
Sets the task state to Active if the task has
been reopened.
task survey events
Task [task]
after
Updates tasks and checks the survey
conditions table to see if a survey related to
this task should be sent.
Test Variables
Requested Item [sc_req_item]
before
Prints a list of variables from the current
items' variable pool.
Prevent changing the table and element
names on an existing dictionary item.
22. Business Rules in the Base System
21
Toggle type
Other Schedule [sc_req_item]
action_list_contextmenu Switches the type.
Transform Validator
Table Transform Map
[sys_transform_map]
before
Verifies that the source and target tables are
not the same for a transform map.
Truncate table name length to 30
Dictionary Entry
[sys_dictionary]
before
Truncates all of the physical table names to
30 characters.
Truncate table name length to 30
Dictionary Entry
[sys_dictionary]
before
Truncates all of the physical table names to
30 characters.
Unload Workflow Version
Workflow Version
[wf_workflow_version]
after
If the published flag changes, the workflow
version is unloaded. If the version is set to
published, then the version and all its related
entries (activities, conditions, transitions,
stages). If the version is set to unpublished
then only the version itself is unloaded. The
unload is handled by the class
WorkflowVersionSynchronizer.
Unpublish other workflow versions
Workflow Version
[wf_workflow_version]
after
When a workflow version is published, this
business rule marks other published
workflow versions for this workflow as
unpublished. This enforces the rule that only
one workflow version can be published at any
one time.
Update Descriptions
Customer Update
[sys_update_xml]
before
Set the description fields for the update,
generating informational data that helps a
user determine what hte update is for.
Update Import Set Complete
Transform History
[sys_import_set_run]
after
Once an import set is complete, this business
rule sets the state of the import set to
Processed.
Update sys_certificate attributes
Attachment [sys_attachment]
after
When an attachment is made on the table
sys_certificate, updates the sys_certificate
attributes.
Update Tomcat Connector Name
Tomcat Connector
[cmdb_ci_tomcat_connector]
before
When the port of the Tomcat Connector
changes, the name of the port changes to
match.
Update Variables Model Information
Variables [var_dictionary]
before
Sets the table based on the variable model.
The model field exists in the variable table
that extends var_dictionary, but the business
rule applies to the var_table so that any
variables tables will get properly set up
without having to copy this business rule for
each variables table.
UpdateSync
Data Source [sys_data_source] after
Updates the sync based on the data source.
Use source script
Field Map
[sys_transform_entry]
before
When the Use Source Script field changes to
true, it uses the source script.
User Deactivate
User [sys_user]
before
Prevents a user from deactivating their own
user record.
User Delete
User [sys_user]
before
Sets a global Rhino variable with the deleted
user's name.
User Delete Self
User [sys_user]
before
Prevents a user from deleting their own user
record.
User preference change
User Preference
[sys_user_preference]
after
Saves the system level changes.
23. Business Rules in the Base System
22
user query
User [sys_user]
before
Queries the active and true fields.
Validate Guest Domain
User [sys_user]
before
Requires the guest user to be in the global
domain.
Validate Scripts
Business Rule [sys_script]
before
Validates business rule scripts.
Validate Spans
Day [sys_cal_day]
before
Checks time spans on calendars, ensuring that
start times and end times are specified and
that the end time comes after the start time. It
also ensures that the times come between
00:00:00 and 24:00:00
validate_only_one_primary
Company [core_company]
before
Ensures that only one company is defined as
Primary.
validate_variable_name
Variable [item_option_new]
before
Validates the names of variables.
Virtual Computer Check
Computer
[cmdb_ci_computer]
before
Validates computer records.
Workflow Activity Changed
Workflow Activity
[wf_activity]
after
Updates the workflow version based on
changes in the Workflow Activity.
Workflow check hasWorkflow
Workflow Version
[wf_workflow_version]
after
Checks that the workflow version has the
Boolean attribute HAS_WORKFLOW.
Workflow initialize
Workflow Version
[wf_workflow_version]
before
When a new workflow is created, this
business rule creates the Begin and End
activities and connects them to each other.
Workflow Item Variables
Global [global]
Workflow Release Lock
Change Request
[change_request]
after
Releases the lock on current that might have
been placed during a workflow reset from the
business rule SNC Approval - Reset
Conditions.
Workflow rename
Workflow Version
[wf_workflow_version]
before
Renames the workflow if the name was
changed for a workflow version.
Workflow Transition Changed
Workflow Transition
[wf_transition]
after
Applies changes made to the workflow
transition to the workflow.
Defines a function wf_variables() that
generates a list of all unique names of
variables for each item that is using the
current workflow. If no items currently have
the workflow attached, then all available
variable names are shown.
workflowTaskTemplateReferenceQualifier Global [global]
WSDLClient
Queue [ecc_queue]
Defines the function
workflowTaskTemplateReferenceQualifier()
that qualifies the template to only include the
task table and any tables that extends it.
before
Parses WSDL in the ECC Queue.
24. Business Rule Error Messages
Business Rule Error Messages
Business Rules Error Logging
When an error occurs in a business rule, the information written to the log is now more readable. Specifically, the
error message is formatted as:
02/10/09 15:37:02 (936) http-8080-Processor22 WARNING *** WARNING *** Evaluator: "badVariable" is not defined.
'''Business Rule:Incident Time Worked''' : Line(11) column(0)
8: } else {
9: var diff = current.time_worked.dateNumericValue();
10: }
*** 11: if (badVariable)
12: gs.print("Print bad variable");
13:
14: if (diff > 0) {
The error message shows the 3 lines above and below the line in error. In addition, if the error occurred in a Server
Script Include, the error message will show the line from the script include and indicate the name of the Script
Include:
02/10/09 15:44:11 (464) http-8080-Processor23 WARNING *** WARNING *** Evaluator: "badVariable" is not defined.
'''Script Include:ScriptIncludeWithError''' : Line(10) column(0)
7: },
8:
9: run: function() {
*** 10: if (badVariable)
11: gs.print("Found a bad variable");
12: },
13:
23
25. Business Rules Best Practices
24
Business Rules Best Practices
Overview
A business rule is a piece of JavaScript that runs when records are displayed, inserted, updated, or deleted, or when a
table is queried. Follow these guidelines to ensure that business rules work efficiently and to prevent unpredictable
results and performance issues.
Know When to Run Business Rules
The When field on the Business Rule form indicates whether the business rule script runs before or after the
current object is saved to the database. The most commonly used business rules are before and after rules.
You can use an async business rule in place of an after business rule. Async business rules are similar to after rules in
that they run after the database commits a change. Unlike after rules, async rules run in the background
simultaneously with other processes. Async business rules allow the system to return control to the user sooner but
may take longer to update related objects.
Follow these guidelines to determine which value to choose for the When field.
Value
Use Case
display Use to provide client scripts access to server-side objects. For more information, see Display Business Rules.
before
Use to update information on the current object. For example, a business rule containing current.state=3; would set the State field
on the current record to the state with a Value of 3.
after
Use to update information on related objects that need to be displayed immediately, such as GlideRecord queries.
async
Use to update information on related objects that do not need to be displayed immediately, such as calculating metrics and SLAs.
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.
26. Business Rules Best Practices
Enclose Code in Functions
Enclose the code in a business rule script inside a function, then call the function to limit the visibility, or scope, of
objects. When code is not enclosed in a function, variables and other objects are available to all other server-side
scripts. This availability can lead to unexpected consequences that are difficult to troubleshoot. Consider this
example:
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.query();
while (gr.next()) {
// do some processing here
}
Because the gr object is not enclosed in a function, all server-side scripts, including script includes and other
business rules, have access to it. Other scripts may also use the common GlideRecord variable name gr. The
duplicate names can conflict and lead to unexpected results. These issues are very difficult to isolate and resolve
because typical debugging methods identify the business rule giving erroneous results rather than the business rule
containing global variables. To avoid this issue, create a function with the same code snippet and call the function in
the business rule script:
processActiveIncidents();
function processActiveIncidents() {
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.query();
while (gr.next()) {
// do some processing here
}
}
This solution is much safer because the scope of the variable gr
is limited to the
processActiveIncidents() function. Therefore, the gr variable does not conflict with gr variables in
other server-side scripts.
In this example, although the gr variable is local to the processActiveIncidents() function, the
processActiveIncidents() function is considered global. Use meaningful function names, for example,
processActiveIncidents() instead of doStuff() to make the purpose of the function clear to other
users.
25
27. Business Rules Best Practices
Use Script Includes Instead of Global Business Rules
A global business rule is any 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.
Most functions defined in global business rules are fairly specific, such as an advanced reference qualifier on one
field of one form. There is no benefit to loading this kind of script on every page.
Script includes only load when called. If you have already written a global business rule, move the function
definition to a script include. The name of the script include must match the name of the function for the script
include to work properly. There is no need to modify any calls to the named function.
Note: Do not convert base system global business rules to script includes. If ServiceNow updates these business rules in the future,
upgrades will skip any that have been customized.
Consider this global business rule:
This script include is a better alternative:
To call the function, use a script like this:
var ref = u_ciRefQual(current.location);
26
28. Business Rules Best Practices
Note: To call a script include function from a list filter or report, select the Client callable check box on the Script Include form.
Global Business Rules with Multiple Functions
If your global business rule contains multiple functions such as the following example, you have two options to
convert it to one or more script includes:
function activeOnly() {
return "active=true";
}
function inActiveOnly() {
return "active=false";
}
function openState() {
return "state=1";
}
Multi-function Global Business Rule Option 1
Put each function in it's own script include. This is easier in the short term by quickly converting a global business
rule to a script include, however it may be more difficult to maintain since these could be related functions and be in
separate records.
Multi-function Global Business Rule Option 2
Put all functions in a script include that defines a class (with no prototype) as in the example below.
var MyUtil = Class.create();
MyUtil.activeOnly = function() {
return "active=true";
}
MyUtil.inActiveOnly = function() {
return "active=false";
}
MyUtil.openState = function() {
return "state=1";
}
This method keeps the related functions together for easier management, however requires you identify each field or
script that calls the functions and update it. For example, a reference qualifier field which previously said
javascript:activeOnly() would become javascript:MyUtil.activeOnly().
27
29. Business Rules Best Practices
Write Small, Specific Business Rules
Small, specific business rules are easier to debug and maintain than large, complex ones. Rather than creating one
business rule that checks and acts upon numerous conditions, create separate business rules for each condition. These
individual business rules make it much easier to maintain each conditional statement and the corresponding logic.
For example, if you've written a single business rule that triggers an event when the priority is 1 and calculates the
fields for a report when the state changes to closed, consider these as two different results to two different conditions
and create two separate business rules. One that triggers an event when the priority is 1 and one that calculates the
fields for a report when the state changes to closed.
Use Conditions
The Condition field on the Business Rule form allows you to create a JavaScript statement for a condition under
which the business rule should execute. If you add a condition statement to this field, ServiceNow evaluates the
condition separately and parses the script only if the condition is true, thus improving performance. It is easier to
debug business rules when you can see which one meet a particular condition and which do not.
While the business rule shown here runs fine, the system loads and evaluates it after every insert or update,
regardless of incident priority or other conditions. There is a single if
statement,
current.getValue('priority') == '1', that determines whether or not the rest of the script should run.
Place this statement in the Condition field, as shown below, to prevent ServiceNow from parsing the script if the
condition is not met.
28
30. Business Rules Best Practices
Use Business Rules to Double-Check Critical Input
If you use a client script to validate data or a reference qualifier to present a filtered list, data may change between
the time the user fills in the fields and the time the user submits the form. This mismatch can cause a conflict or
error. Business rules are an effective way to double-check critical input.
For example, a request allows users to reserve items. When users fill out the request form, they can only select
currently available items. If two people fill out a particular form at once and select the same item, the item appears to
be available to both people because neither of them has submitted the form yet. If there is no business rule to
double-check availability, ServiceNow assigns the same item to both requests. By using a business rule to re-verify
item availability when the form is submitted, the second person receives a warning or other notification indicating
the item has already been taken.
Condition: current.cmdb_ci.changes()
Script:
/************************
*
* Double-check to ensure that no one else has selected and
* submitted a request for the same configuration item (CI)
*
************************/
doubleCheckCiAvailability();
function doubleCheckCiAvailability() {
var lu = new LoanerUtils();
if (!lu.isAvailable(current.cmdb_ci, current.start_date,
current.end_date)) {
gs.addErrorMessage(gs.getMessage('Sorry, that item has already
been allocated'));
current.cmdb_ci = 'NULL';
}
}
29
31. Accessing the Workflow Scratchpad from Business Rules
Accessing the Workflow Scratchpad from
Business Rules
Functionality described here requires the Admin role.
Name: Access Workflow Scratchpad from Business Rules
Type: Business Rule
Table: sc_req_item (Requested Item)
Description: A catalog item has been requested, the attached workflow contains a run script activity that populates a
value in the scratchpad. From a business rule running on the requested item, we want to retrieve or set scratchpad
values.
Parameters: n/a
Script:
//the run script activity sets a value in the scratchpad
workflow.scratchpad.important_msg = "scratch me";
//get the workflow script include helper
var workflow = new Workflow();
//get the requested items workflow context
//this will get all contexts so you'll need to get the proper one if
you have multiple workflows for a record
var context = workflow.getContexts(current);
//make sure we have a valid context
if (context.next()) {
//get a value from the scratchpad
var msg = context.scratchpad.important_msg;
//msg now equals "scratch me", that was set in the run script
activity
//add or modify a scratchpad value
context.scratchpad.status = "completed";
//we need to save the context record to save the scratchpad
context.update();
}
30
32. Building an OR Query in a Business Rule
Building an OR Query in a Business Rule
Overview
An OR condition can be added to any query part within a business rule using the addOrCondition() method.
Example 1
Here is a query that would be used to find all the incidents that have either a 1 or a 2 priority. Your initial addQuery()
condition is defined as a variable, then use the variable to add your OR condition.
var inc = new GlideRecord('incident');
var qc = inc.addQuery('priority', '1');
qc.addOrCondition('priority', '2');
inc.query();
while (inc.next()) {
// processing for the incident goes here
}
Example 2
A more complex example, using two query condition variables doing the equivalent of "(priority = 1 OR priority =
2) AND (impact = 2 OR impact = 3)".
var inc = new GlideRecord('incident');
var qc1 = inc.addQuery('priority', '1');
qc1.addOrCondition('priority', '2');
var qc2 = inc.addQuery('impact', '2');
qc2.addOrCondition('impact', '3');
inc.query();
while (inc.next()) {
// processing for the incident goes here
}
31
33. Article Sources and Contributors
Article Sources and Contributors
Business Rules Source: http://wiki.servicenow.com/index.php?oldid=191000 Contributors: CapaJC, Cheryl.dolan, Doug.penta, Emily.partridge, G.yedwab, Guy.yedwab, John.andersen,
John.roberts, Joseph.messerschmidt, Michelle.Corona, Neola, Rachel.sienko, Steve.wood, Suzannes, Vaughn.romero
Business Rules in the Base System Source: http://wiki.servicenow.com/index.php?oldid=166001 Contributors: CapaJC, G.yedwab, Guy.yedwab, John.roberts, Joseph.messerschmidt, Neola,
Steve.wood, Suzannes, Vaughn.romero, Wallymarx
Business Rule Error Messages Source: http://wiki.servicenow.com/index.php?oldid=76200 Contributors: Guy.yedwab, Jay.berlin, Neola, Steve.wood, Vhearne
Business Rules Best Practices Source: http://wiki.servicenow.com/index.php?oldid=198661 Contributors: Chuck.tomasi, David.Bailey, Peter.smith
Accessing the Workflow Scratchpad from Business Rules Source: http://wiki.servicenow.com/index.php?oldid=84656 Contributors: G.yedwab, Joe.Westrich, John.roberts,
Joseph.messerschmidt, Neola, Steve.wood
Building an OR Query in a Business Rule Source: http://wiki.servicenow.com/index.php?oldid=100069 Contributors: CapaJC, Don.Goodliffe, G.yedwab, Guy.yedwab, Jared.laethem,
Joseph.messerschmidt, Neola, Steve.wood, Vhearne
32