Top Banner
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 Business Rules
34

Business rules

May 08, 2015

Download

Education

Govind Reddy

Service now Business Rules
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 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

Business Rules

Page 2: Business rules

Business Rules 1

Business Rules

OverviewA business rule is a piece of JavaScript configured to run when a record is displayed, inserted, updated, deleted, orwhen a table is queried. A business rule can be set to run before or after the database action has occurred. In the caseof a query, the business rule runs before the database operation, so that the data returned to the user is appropriate tohis system privileges (user roles). A typical business rule might execute a script after a user updates an incident orescalates the priority of a change request. Use a business rule to create new events for email notification and scriptactions.

Business Rule Process Flow

Note that business rules apply consistently to records regardless of whether they are accessed through forms, lists, orweb services. This is one major difference between business rules and client scripts, which only apply when editingthrough the form.

Page 3: Business rules

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 ruleis 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 theorder 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 tellServiceNow to evaluate the condition separately and parse the script only if the condition is true. If you decide to include the conditionstatement in the script, leave this field blank. To have the instance reevaluate the condition statement a second time before running anasync 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.

Page 4: Business rules

Business Rules 3

Business Rule ScriptingYou create scripts in business rules with JavaScript. The following are the predefined variables that help referencethe 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 GlobalSystem provided variables, such as current, previous, and g_scratchpad are global across all businessrules that run for a transaction. User created variables are also globally scoped by default. This means that if a newvariable is declared in an order 100 business rule, the business rule that runs next at order 200 will also have accessto 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 protectsyour variables from conflicting with system variables or global variables in other business rules not wrapped in afunction. Additionally, variables such as current must be available when a function is invoked in order to beused.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 withother functions using a variable named gr.

myFunction();

function myFunction() {

var gr = new GlideRecord('incident');

gr.query();

while (gr.next()) {

//do something

}

}

Page 5: Business rules

Business Rules 4

Aborting a Database Action in a Business RuleDuring a before business rule script you can cancel, or abort, the current database action by using thecurrent.setAbortAction(true) method. For example, if your business rule is executed with a setting ofbefore during an Action of Insert, and you have a condition in the script that, when met, callscurrent.setAbortAction(true), then the new record stored in current will not be created in thedatabase.

Global Business RulesBusiness rules marked as global in the Table column are loaded and initialized at the beginning of each interactionbetween a user and the platform. Global business rules ignore the Condition field. Therefore, unless the script iswrapped 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 rulesare 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 bemade in before business rules, which then lets the system update the record. Any after business rules should onlyreact to the update to do things like create events or update related records (like the incidents related to an updatedchange), and therefore should not use current.update().

Display Business RulesDisplay rules are processed when a user requests a record form. The data is read from the database, display rules areexecuted, and then the form is presented to the user. The current object is available and represents the recordretrieved from the database. Any field changes are temporary since they are not yet submitted to the database. To theclient, the form values appear to be the values from the database; there is no indication that the values were modifiedfrom 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 sentto the client as part of the form. This can be useful when you need to build client scripts that require server data thatis not typically part of the record being displayed. In most cases this would require a client script making a call backto the server. If the data can be determined prior to the form being displayed, it will be more efficient to provide thedata to the client on the initial load. The form scratchpad object is an empty object by default, and only used to storename: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;

Page 6: Business rules

Business Rules 5

//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 RuleSometimes 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 triggeredthe 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 ActiveRequirements// 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());

}

Page 7: Business rules

Business Rules 6

Enhancements

AspenIn the Aspen release, two Async Delete Warning client scripts use showFieldMsg() instead ofaddInfoMessage() when warning against using Current in an async business rule.

Business Rules in the Base System

OverviewThe table on this page includes a description of each business rule included in the out-of-box ServiceNow systemand a short description of what it it does. Depending on the version of ServiceNow you are using, some businessrules on this list might not be present or might operate in a slightly different way. This list includes business rulesinstalled 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 aprocess guide is running.

Adjust install counts for licenses Software [cmdb_ci_spkg] after Updates the install counts on the Softwaretable for all licenses with non-discoverablekeys.

Affected ci notifications Task [task] async Notifies subscribers when CIs are affected byan incident.

Affected cost center notifications Task [task] async Notifies cost center subscribers when CIsrelated to the cost center are affected by anincident.

Affected group notifications Task [task] async Notifies group subscribers when CIs assignedto the group are affected by an incident.

Affected location notifications Task [task] async Notifies location subscribers when CIs in aspecific 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 Planfield will be emptied, because both cannot beused.

approval events Approval[sysapproval_approver]

after Generates all of the events in the approvalprocess. Important for driving emailnotifications 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 SoftwareLicense table for all licenses withnon-discoverable keys.

Asset Adjust Used License Count Software License Instance[ast_license_instance]

after Updates the install counts on the SoftwareLicense Instance table for all licenses withnon-discoverable keys.

Page 8: Business rules

Business Rules in the Base System 7

Assign from Stock Requested Item [sc_req_item] after If a requested item's Configuration Item ischanged to an existing CI record, the businessrule will update the CI record to indicate thatit is being assigned to the requester.

Attach Delivery Plan Change Request[change_request]

after If a change request does not have a deliveryplan attached, this business rule will attach adelivery plan.

Attachment events Attachments [sys_attachment] after Generates events based on an attachmentbeing 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 ismarked as approved as part of an existingdelivery plan.

Auto Close On Approval Catalog Task [sc_task] before Auto-closes the current catalog task if it ismarked as approved as part of an existingdelivery plan.

Auto set workflow from workflow version Workflow Context[wf_context]

before Enforces that the Workflow Version'sWorkflow field matches the WorkflowContext's Workflow field.

Auto start on context Workflow Context[wf_context]

after If the auto_start flag is true on a workflowcontext, this business rule drives the autostart.

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 fieldsto non-boolean fields.

Build Connection URL Data Source [sys_data_source] before Generates the connection URL for the datasource.

Calc SLAs on Display Task [task] display Calculates the stage and elapsed time of anSLA affected by an incident when theincident form displays.

Calculate Article Rating Knowledge Feedback[kb_feedback]

async Calculates the article rating based on theaggregates all of the ratings cast.

Calculate expires in days X.509 Certificate[sys_certificate]

before Calculates the amount of time left before theX.509 Certificate expires.

Calculate Request Item Due Date Requested Item[sc_request_item]

before Calculates the due date of the request item byadding the delivery time to the time that therecord was assigned.

Calculate Total Delivery Time Execution Plan Task[sc_cat_item_delivery_task]

before Calculates the total delivery time for anexecution plan.

calculatePriority Global [global] Calculates the priority level used for priorityfields.

Page 9: Business rules

Business Rules in the Base System 8

Cancel Workflows Upon Cancellation Task [task] after If the task State changes to ClosedIncomplete (4), cancel related workflows sothat tasks do not remain active.

Cascade Request Approval to RequestItem

Request [sc_request] after Cascades any changes made to the approvalfield of a service catalog request to therequested items attached to that request.

certificate events X.509 Certificate[sys_certificate]

before Generates events based on changes to theX.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, orTimezone formatting in their user profile, thisbusiness rule updates their current session tomatch the new settings.

Change Phase Events Change Phase [change_phase] after Generates the events related to ChangePhases after the Change Phase is loaded.

Change Phase Events Before Change Phase [change_phase] before Generates the events related to ChangePhases before the Change Phase is loaded.

Change state on closed Insert Incident [incident] before Updates the state field in the Task table tomatch the incident_state field when theincident is closed.

change reopen Change Request[change_request]

before If the state is changed on a Change Requestthat was previously closed, this business rulereturns the Request to active.

Check max_length Variables [var_dictionary] before Enforces a maximum length on variables of40 characters.

Choice Events Choices [sys_choice] after Generates the events related to Choicesbefore 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 tablevalue is cleared.

Close Parent if Required Requested Item[sc_request_item]

after If a requested item is either cancelled ordelivered, the business rule checks to see ifthere are other active requested itemsattached to the parent request. If there arenone, then the parent request is updated withthe same state.

Close Tasks Due to Cancellations Requested Item[sc_request_item]

after If a requested item is cancelled, all of thetasks created by that requested item areclosed.

Close Ticket Change Task [change_task] before If the Change Task is marked either ascomplete or cancelled, the business rulecloses the ticket and populates fields relatedto closure (e.g. Work End).

Close Ticket Catalog Task [sc_task] before If the Catalog Task is marked either ascomplete or cancelled, the business rulecloses the ticket and populates fields relatedto closure (e.g. Work End).

cmdb synch event Configuration Item [cmdb_ci] after Generates a roll-up event every time a CI ischanged.

Page 10: Business rules

Business Rules in the Base System 9

cmdbCIChildren Global [global] A script which lists all of the children of aconfiguration item.

cmdb_rel_ci synch event CI Relationship [cmdb_rel_ci] after Generates a roll-up event every time a CI ischanged.

cmdb_rel_suggest_relationshipGetChoices Global [global] A script which lists all of the choices forsuggested relationships.

Company Projection Incident [incident] before Populates the company field with the caller'scompany field if an incident has a caller listedbut no company listed.

Condition Field validation Condition Checks[cmn_condition_check]

before Enforces the requirement that the conditionfield is a reference to cmn_condition_checker

Contain Changes Contained Role[sys_user_role_contains]

after Applies changes in the Contained Role tableto the role manager.

Contract Instance Lease Instance[ast_contract_instance]

before Populates the Contract Instance withinformation from the Contract record, andfrom 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 aworkflow, this business rule generates thenext activity in the workflow instance basedon the workflow itself.

Create default conditions Workflow Activity[wf_activity]

after Generates default conditions for eachworkflow activity if the activity has noparent.

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 thecurrent relationship.

Create Inventory Item Requested Item [sc_req_item] after When a requested item's stage reachesComplete, it generates a CMDB record forthe requested item.

Create module table Module [sys_app_module] after When a module is inserted, it checks if thereis a table already tied to the module. If not, itcreates a table.

Create or Remove Text Index Dictionary Entry[sys_dictionary]

before If the attribute text_index is changed, thebusiness rule either requests a text index ordisposes of the existing text index, asappropriate. Note that the business ruleCreate Text Index actually performs the textindex creation.

Create Request Item Child Tasks Requested Item [sc_req_item] after When a requested item is created, thisbusiness rule generates the execution plantasks 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 SystemDictionary, this business rule will index thetext within all of the records for use in theglobal text search.

CreateElement Dictionary Entry[sys_dictionary]

after Creates an Element in the Dictionary.

Page 11: Business rules

Business Rules in the Base System 10

CTI Processing Global [global] Parses the payload from a URL generated byCTI. For more information, see ComputerTelephony 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 userdelegates unless they are an administrator.

Delete databases on change Round Robin Definition[jrobin_definition]

after If a Round Robin Definition changes, thisbusiness rule deletes any databases that wereusing it.

Delete databases on change Round Robin Archive[jrobin_archive]

after If a Round Robin Archive changes, thisbusiness rule deletes any databases that wereusing it.

Delete Impacted Services Task [task] after Deletes affected services when the task isdeleted.

Delete parent workflow Workflow Version[wf_workflow_version]

after If the last remaining workflow version of aparent workflow is deleted, this business ruledeletes the parent workflow.

Delete software license instance Software Instance[cmdb_software_instance]

after If the software instance is deleted from theCMDB table, this business rule deletes thesoftware 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 tasksgenerated by the requested items are deletedas well. It also rebalances the request's priceto reflect the change.

Delete Text Index Dictionary Entry[sys_dictionary]

after Queues the text index for deletion.

deleteAllRecords Global [global] A function for deleting all records from aparticular table.

Dictionary change Dictionary Entry[sys_dictionary]

after Flushes the system's cache after a change inthe 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] A function for creating a user from a stringvalue. It splits the value at the space, and thenproperly capitalizes the first and last names.

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 ECCQueue.

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 ensurethat ${body} appears in the style field.

Page 12: Business rules

Business Rules in the Base System 11

emailsToUsers Global [global] This function converts an email address touser names. Ifglide.ui.activity.email.use_display is set totrue, this function is called in the activityheaders of emails.

Ensure unique target field Field Map[sys_transform_entry]

before Enforces target field uniqueness whenbuilding 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 thatapplied to the field.

Flush Form Cache Client Script[sys_script_client]

after Flushes the cache every time a client script ischanged or updated.

Flush Form Cache UI Policy [sys_ui_policy] after Flushes the cache every time a UI Policy ischanged or updated.

Flush Form Cache UI Policy Action[sys_ui_policy_action]

after Flushes the cache every time a UI PolicyAction is changed or updated.

Flush RealForm Cache Module [sys_app_module] after Flushes the realform cache every time amodule is changed or updated.

Flush RealForm Cache Application[sys_app_application]

after Flushes the realform cache every time anapplication is changed or updated.

Flush RealForm Cache UI View [sys_ui_view] after Flushes the realform cache every time a UIView is changed or updated.

Flush the activity definition cache Workflow Activity Definition[wf_activity_definition]

before Flushes the activity definition cache everytime an activity definition is changed orupdated.

Flush Variables Cache Variables [var_dictionary] after Flushes the cache every time a variable ischanged or updated.

Force Priority Calc Incident [incident] before Forces calculation of priority based on impactand 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 thedata source.

genChangePlanURL Global [global] A function for generating a URL for thechange plan.

Generate activity sequences Workflow Version[wf_workflow_version]

before Generates a list of sys_ids for each paththrough the workflow, which is used to checkif 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 longitudecoordinates.

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 asys id.

Page 13: Business rules

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 displayvalues and returns a query condition that willquery on the group type sys_id values.

getGroupMembersM2M Gets the list of users who are members of aparticular group.

GetIDValue Global [global] Gets the sys_id and the display values for agiven table.

getLDAPSources Global [global] Gets the list of LDAP Sources.

getMYApprovals Global [global] Gets the list of the current user's approvalsand assignments.

getNextObjNumberPadded Global [global] Gets the next number in a series with thepadding specified by the NumberMaintenance settings.

getNodesInSameCluster Global [global] Gets the nodes in the same cluster.

getQuestionOrder Question Choices[question_choice]

before_display Gets the order for question choices.

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 haveat least one role. Has optional parameters toallow the exclusion of certain roles, orinclusion of only certain particular roles.Optional: queryCondition 'IN' or 'NOT IN' toinclude or exclude. Optional: roleList - acomma 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 auser.

getUserHomepages Global [global] Gets the list of homepages that belong to auser.

get_lat_long Location [cmn_location] async Gets the latitude and longitude of an addressfor a location record.

get_lat_long Company [core_company] async Gets the latitude and longitude of an addressfor a company record.

global events Global [global] Generates events that apply globally.

Google Map API Global [global] Generates the API used to communicate withGoogle Maps.

Group Member Add Group Member[sys_user_grmember]

after When a user is added to a group, this businessrule adds all of the roles that group membersshould inherit.

Group Member Delete Group Member[sys_user_grmember]

after When a user is removed from a group, thisbusiness rule removes all of the roles thatgroup members had inherited.

Page 14: Business rules

Business Rules in the Base System 13

group query Group [sys_user_group] after Checks to see if a user is a member of agroup.

Group Role Changed Group Role[sys_group_has_role]

after If a role is either marked or unmarkedInherited, this business rule applies the role toall group members or removes the role fromall group members.

Group Role Deleted Group Role[sys_group_has_role]

after If a role is deleted, this business rule deletesthe role from members and from childgroups.

groups, banners Global [global] Prevents recursive company loops.

incident autoclose Incident [incident] after Automatically closes incidents that areresolved and have not been updated, based onthe glide.ui.autoclose.time property.

Incident Create Knowledge Incident [incident] after Creates a knowledge article from the incidentand formats the output if the "CreateKnowledge" checkbox is selected.

incident events Incident [incident] after Generates the events related to incident.

incident functions Global [global] Defines three useful functions for Incidents:

• incidentGetViewName()• incidentGetCaller()• sys_userGetEmailAddress

incident query Incident [incident] before Queries the incident if the user has the itilrole. Enables ESS users on the watch list tosee Incidents.

incident reopen Incident [incident] before Reopens an incident if the state changes toanything other than closed.

Incident Time Worked Incident [incident] after Updates the Time Worked field every timethe incident record is worked on.

Insert Change Phases Change Request[change_request]

after Generates the change phases based on thechange request.

insert_change Change Request[change_request]

before Generates a new number for a new ChangeRequest (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 theidentification number sequentially, using theconfigured prefix and padding.

insert_lease Lease [ast_lease] before Generates a new number for a new Lease (seeNumber 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 ServiceContract (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 theproperty glide.ui.advanced. If this propertyis true, it enable the advanced UI.

Page 15: Business rules

Business Rules in the Base System 14

itil appointment Appointment[itil_appointment]

after Creates events for updates or inserts on theAppointment table.

KB Events Article KB Submission[kb_submission]

after Creates events for an article being createdfrom a submission.

KB Events Duplicate KB Submission[kb_submission]

after Creates events for an article being closed as aduplicate.

KB Events Invalid KB Submission[kb_submission]

after Creates events for an article being closed forbeing 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 Userrecord 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 Userrecord is deleted.

load ajax globals AJAX Script [sys_script_ajax] after Reloads AJAX global scripts when they arechanged.

load globals Business Rule [sys_script] after Reloads global business rules when they arechanged.

Location - generate full name Location [cmn_location] after Calls HeirarchicalReference to generate thefull location name.

Lock Out Inactive Users User [sys_user] after If a user record is set to active = false, thisbusiness rule sets locked_out = true.

Lock Out User User [sys_user] after If locked_out = true, it kills any sessionsinitiated by the locked out user.

mark closed Task [task] before If the state changes to Closed, Active is set tofalse.

Mark Request Closed Request [sc_request] before If a request moves to closed, this businessrule sets the end-time values and marks therequest as inactive.

Mark Submission Closed KB Submission[kb_submission]

before If the status is set to closed, the active flag isset to false.

mark_closed Incident [incident] before If the incident state is set to Closed, theincident is set to Inactive, the closed_by andclosed time values are set, and the duration iscalculated.

mark_closed Change Request[change_request]

before If the change state is set to closed, the activeflag is set to false.

mark_closed Problem [problem] before If the problem is set to closed, the active flagis set to false, and the closed_by andclosed_at values are set.

Metric definition CI Metric [cmdb_metric] after Defines the metrics. See Metric DefinitionPlugin.

Metric population CI Metric [cmdb_metric] after Populates the defined metrics. See MetricDefinition 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.

Page 16: Business rules

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 asinactive if a task is cancelled.

No Duplicates Dictionary Entry[sys_dictionary]

before Enforces dictionary entry uniqueness.

Notification Device View Filter Global [global] Filters notification devices based on role.

Outage Calculations Outage [cmdb_ci_outage] before If beginning and end times are present,calculates the outage duration.

Package Adjust Install Count Software License Instance[ast_license_package_instance]

after Adjusts the install count of software.

Pad Numbers Sys number [sys_number] async When the maximum digit changes, thisbusiness rule adds padding to the number.

Parent Bumper Plan Sequencing[sc_cat_item_dt_mtom]

after Updates the delivery plan based on thedelivery plan tasks.

Parent changes Group [sys_user_group] after If a group changes parent groups, thisbusiness rule applies the appropriate roles.

Post Outage to News Business Service[cmdb_ci_service]

after If an outage occurs, it creates a new newsarticle.

Prevent Creation of 2nd Default Update Set [sys_update_set] Before Prevents users from creating an update setcalled "Default" when there is an existingupdate set of that name.

Prevent Recursion Table class [sys_db_object] before Prevents recursion when a table's super_classchanges.

Prevent Recursion Category [sc_category] before Prevents recursion when a category's parentchanges.

Prevent Recursion Group [sys_user_group] before Prevents recursion when a group's parentchanges.

Prevent removal/update of primary CI Task [task_ci] before To keep information synchronized, thisbusiness rule prevents removal of an affectedCI 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 theDefault 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 toanother state, this business rule marks theactive 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 processesactive 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 toproperties.

Page 17: Business rules

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 fieldeach 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 withoutreferencing a table.

Reject Parent Catalog Task [sc_task] after If a catalog task is rejected, the parent requestis rejected as well.

Reload import sets Import Set [sys_import_set] after Sets all import sets to pending, so that theywill 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 withgenerating reports:

• getGroupMembers - Returns an array ofall the users that are in any of the groupsspecified.

• getGroupMembersGivenGroupName -Add members of a specified group into anarray.

• getGroupMembersGivenGroupID -Add members of a specified group into anarray.

• getAllMembersOfMyGroups - Gets anarray of all users that belong to the samegroups 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 businessrule closes child requests, requested items,and cancels approvals.

Request item handling Workflow Version[wf_workflow_version]

before Sets up the workflow version to handlerequested items correctly.

Request reopened Request [sc_request] before If the user changed the state to be not closed,this business rule reopens the request bysetting it active.

Reset Binding Change Task [change_task] before Resets the state binding on a change taskwhen it is re-entered.

Reset Binding Catalog Task [sc_task] before Resets the state binding on a catalog taskwhen 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] Returns the stages for a Request Item as achoice list.

sc_task_events Catalog Task [sc_task] after Generates the events for catalog tasks.

Search Group Delete Text Search Groups [ts_group] before Deletes a search group.

Page 18: Business rules

Business Rules in the Base System 17

Search Table Info for Group Text Search Tables [ts_table] after Generates table information for the searchgroups.

Search Table Preference Text Search Tables [ts_table] after Applies the users' preferences on searchgroups.

Set Active Flag Requested Item [sc_req_item] before If a requested item is set to complete, thisunmarks the active flag and cancels anycurrently 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, thisbusiness rule makes a note of the fact on thefeedback table.

Set Flagged Status Knowledge Feedback[kb_feedback]

after Ensures that the flag on the knowledge articlematches 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_parentflag on an activity.

Set javascript class name Workflow Activity[wf_activity]

before Enforces propercase for Javascript class namein the activity.

Set label and help Variables [var_dictionary] after Deletes related entries, and updates therelated documentation entries.

Set Parent Change Task [change_task] before Sets the Change Request as the ChangeTask'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, thebusiness rule marks the resolved checkbox.

Set selected color Graph Line[jrobin_graph_line]

before Sets the graph line according to the colorpicker.

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 globalusers.

Set wait_for to workflow Group Approval[sysapproval_group]

before Sets the wait_for field to be 'workflow' if thisapproval 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 assignedto 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 whenthe group is deleted.

SNC - ITIL - Close Related Problem [problem] after Closes any incidents that are related to thecurrent problem.

Page 19: Business rules

Business Rules in the Base System 18

SNC - ITIL - Close Related Change Request[change_request]

after Find related problems for a change_requestand close them.

SNC - ITIL - Close Related Global [global] Find related tasks for the current task andclose them.

SNC - ITIL - Close Related Incident [incident] after Finds related incidents for the currentincident and closes them.

SNC - Match state to approval Group approval[sysapproval_group]

before Makes sure the state matches the approvalvalue.

SNC - Moot user approval Group approval[sysapproval_group]

after Set all of the pending user approvals for thisgroup approval to Not Required.

SNC - Run parent workflows Task [task] after Restarts a running parent workflow, when thecurrent task is completed.

SNC - Run parent workflows Approval[sysapproval_approver]

after Run any workflows so the approval's statecan be checked.

SNC - Run parent workflows Group Approval[sysapproval_group]

after Run any workflows so the group approval'sstate can be checked.

SNC Approval - Reset conditions Change Request[change_request]

before The reset conditions for approvals. Note: thisbusiness rule is inactive by default. Thebusiness rule provides instructions foractivating the business rule within thecomments 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 changesglobally.

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] Defines two functions for getting values fromthe dictionary:

• doesEntryFloat• getDictionaryEntry

SNC Global Listener Global [global] Gets control for each field that has anattribute of "listen". If a change has not beenauthorized then a problem record will be cutfor the change.

SNC Invalidate LDAP Import Export Map[sys_impex_map]

after Flushes the cache after an update of theimport/export map.

SNC Invalidate LDAP1 Field Map [sys_impex_entry] after Flushes the cache after an update of theimport/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 relatedproblems and posting all of the records toDefinitive Software Library.

SNC Release Delete Phases Release [release_project] async Deletes release phases upon completion.

Page 20: Business rules

Business Rules in the Base System 19

SNC Release feature Feature [release_feature] before Verifies that:

• The feature is part of a product and is partof 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 theapproval.

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 relatedproduct manager.

SNC Release project complete Release [release_project] before If state changes to complete, then markrelease 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] A function to gets a reference qualifier for atemplate group.

SNC Template Query Template [sys_template] before Filters the templates by user, so that userswill only see templates that are available forthem wherever they are in the system.Deactivating the SNC Template Querybusiness rule has the effect of allowing usersto see all templates. The Aspen releaseincludes a new version of the Read ACL forsys_template and the template query businessrules to ensure that users can see applicabletemplates.

SNC Transaction History Sys trend [sys_trend] after Send transaction history records back to /hiperiodically.

SOAPClient Queue [ecc_queue] before Parses SOAP packages.

Stamp Approvals Task [task] before Marks approvals with a timestamp when theapproval status changes.

Start Change Tasks Change Request[change_request]

after Starts the change tasks when the change isapproved.

Start Peer Tasks (change_task) Change Task [change_task] after When a change task ends, this business rulestarts the next change task.

Start Tasks Requested Item [sc_req_item] after When a requested item is approved, thisbegins the first catalog task.

Start Workflow Requested Item [sc_req_item] before When a requested item is approved, thisinitializes the workflow, and puts thevariables from the requested item into theworkflow if the names match.

String class extensions Global [global]

Page 21: Business rules

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 areupdated.

Sync CI answers with CI modules sys_wizard_answer after Along with the Sync Interceptor Answerswith CI Modules business rule, synchronizesroles and active fields for table-specificCMDB modules with their correspondingcmdb_ci.do interceptor answers. Thisbehavior 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 CIsrelated list. To keep informationsynchronized, if the CI on the form changes,the old one is removed from the related listand the new one is added.

Sync Interceptor Answers with CIModules

sys_app_module after Along with the Sync CI answers with CImodules business rule, synchronizes roles andactive fields for table-specific CMDBmodules with their corresponding cmdb_ci.dointerceptor answers. This behavior iscontrolled 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 whenapproved.

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.schedulersis modified.

System Update Confirm Queue [ecc_queue] async Confirms a system update.

sys_dictionary Global [global] Prevent changing the table and elementnames on an existing dictionary item.

task closer Task [task] before Sets the task state to Closed if the task hasbeen closed.

task events Task [task] after Generates the events for a task when anapproval is rejected or approved.

task reopener Task [task] before Sets the task state to Active if the task hasbeen reopened.

task survey events Task [task] after Updates tasks and checks the surveyconditions table to see if a survey related tothis task should be sent.

Test Variables Requested Item [sc_req_item] before Prints a list of variables from the currentitems' variable pool.

Page 22: Business rules

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 arenot the same for a transform map.

Truncate table name length to 30 Dictionary Entry[sys_dictionary]

before Truncates all of the physical table names to30 characters.

Truncate table name length to 30 Dictionary Entry[sys_dictionary]

before Truncates all of the physical table names to30 characters.

Unload Workflow Version Workflow Version[wf_workflow_version]

after If the published flag changes, the workflowversion is unloaded. If the version is set topublished, then the version and all its relatedentries (activities, conditions, transitions,stages). If the version is set to unpublishedthen only the version itself is unloaded. Theunload is handled by the classWorkflowVersionSynchronizer.

Unpublish other workflow versions Workflow Version[wf_workflow_version]

after When a workflow version is published, thisbusiness rule marks other publishedworkflow versions for this workflow asunpublished. This enforces the rule that onlyone workflow version can be published at anyone time.

Update Descriptions Customer Update[sys_update_xml]

before Set the description fields for the update,generating informational data that helps auser determine what hte update is for.

Update Import Set Complete Transform History[sys_import_set_run]

after Once an import set is complete, this businessrule sets the state of the import set toProcessed.

Update sys_certificate attributes Attachment [sys_attachment] after When an attachment is made on the tablesys_certificate, updates the sys_certificateattributes.

Update Tomcat Connector Name Tomcat Connector[cmdb_ci_tomcat_connector]

before When the port of the Tomcat Connectorchanges, the name of the port changes tomatch.

Update Variables Model Information Variables [var_dictionary] before Sets the table based on the variable model.The model field exists in the variable tablethat extends var_dictionary, but the businessrule applies to the var_table so that anyvariables tables will get properly set upwithout having to copy this business rule foreach 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 totrue, it uses the source script.

User Deactivate User [sys_user] before Prevents a user from deactivating their ownuser record.

User Delete User [sys_user] before Sets a global Rhino variable with the deleteduser's name.

User Delete Self User [sys_user] before Prevents a user from deleting their own userrecord.

User preference change User Preference[sys_user_preference]

after Saves the system level changes.

Page 23: Business rules

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 globaldomain.

Validate Scripts Business Rule [sys_script] before Validates business rule scripts.

Validate Spans Day [sys_cal_day] before Checks time spans on calendars, ensuring thatstart times and end times are specified andthat the end time comes after the start time. Italso ensures that the times come between00:00:00 and 24:00:00

validate_only_one_primary Company [core_company] before Ensures that only one company is defined asPrimary.

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 onchanges in the Workflow Activity.

Workflow check hasWorkflow Workflow Version[wf_workflow_version]

after Checks that the workflow version has theBoolean attribute HAS_WORKFLOW.

Workflow initialize Workflow Version[wf_workflow_version]

before When a new workflow is created, thisbusiness rule creates the Begin and Endactivities and connects them to each other.

Workflow Item Variables Global [global] Defines a function wf_variables() thatgenerates a list of all unique names ofvariables for each item that is using thecurrent workflow. If no items currently havethe workflow attached, then all availablevariable names are shown.

Workflow Release Lock Change Request[change_request]

after Releases the lock on current that might havebeen placed during a workflow reset from thebusiness rule SNC Approval - ResetConditions.

Workflow rename Workflow Version[wf_workflow_version]

before Renames the workflow if the name waschanged for a workflow version.

Workflow Transition Changed Workflow Transition[wf_transition]

after Applies changes made to the workflowtransition to the workflow.

workflowTaskTemplateReferenceQualifier Global [global] Defines the functionworkflowTaskTemplateReferenceQualifier()that qualifies the template to only include thetask table and any tables that extends it.

WSDLClient Queue [ecc_queue] before Parses WSDL in the ECC Queue.

Page 24: Business rules

Business Rule Error Messages 23

Business Rule Error Messages

Business Rules Error LoggingWhen an error occurs in a business rule, the information written to the log is now more readable. Specifically, theerror 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 ServerScript Include, the error message will show the line from the script include and indicate the name of the ScriptInclude:

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:

Page 25: Business rules

Business Rules Best Practices 24

Business Rules Best Practices

OverviewA business rule is a piece of JavaScript that runs when records are displayed, inserted, updated, or deleted, or when atable is queried. Follow these guidelines to ensure that business rules work efficiently and to prevent unpredictableresults and performance issues.

Know When to Run Business RulesThe When field on the Business Rule form indicates whether the business rule script runs before or after thecurrent 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 inthat they run after the database commits a change. Unlike after rules, async rules run in the backgroundsimultaneously with other processes. Async business rules allow the system to return control to the user sooner butmay 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 fieldon 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 RulesAvoid using current.update() in a business rule script. The update() method triggers business rules torun 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, andafter business rules are best used for updating related, not current, objects. When a recursive business rule isdetected, the system stops it and logs the error in the system log. However, current.update() causes systemperformance issues and is never necessary.You can prevent recursive business rules by using the setWorkflow() method with the false parameter. Thecombination of the update() and setWorkflow() methods is only recommended in special circumstanceswhere the normal before and after guidelines mentioned above do not meet your requirements.

Page 26: Business rules

Business Rules Best Practices 25

Enclose Code in FunctionsEnclose the code in a business rule script inside a function, then call the function to limit the visibility, or scope, ofobjects. When code is not enclosed in a function, variables and other objects are available to all other server-sidescripts. This availability can lead to unexpected consequences that are difficult to troubleshoot. Consider thisexample:

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 otherbusiness rules, have access to it. Other scripts may also use the common GlideRecord variable name gr. Theduplicate names can conflict and lead to unexpected results. These issues are very difficult to isolate and resolvebecause typical debugging methods identify the business rule giving erroneous results rather than the business rulecontaining global variables. To avoid this issue, create a function with the same code snippet and call the function inthe 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 theprocessActiveIncidents() function. Therefore, the gr variable does not conflict with gr variables inother server-side scripts.In this example, although the gr variable is local to the processActiveIncidents() function, theprocessActiveIncidents() function is considered global. Use meaningful function names, for example,processActiveIncidents() instead of doStuff() to make the purpose of the function clear to otherusers.

Page 27: Business rules

Business Rules Best Practices 26

Use Script Includes Instead of Global Business RulesA global business rule is any business rule where the selected Table is Global. Any other script can call globalbusiness 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 onefield 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 functiondefinition to a script include. The name of the script include must match the name of the function for the scriptinclude 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);

Page 28: Business rules

Business Rules Best Practices 27

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 FunctionsIf your global business rule contains multiple functions such as the following example, you have two options toconvert 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 1Put each function in it's own script include. This is easier in the short term by quickly converting a global businessrule to a script include, however it may be more difficult to maintain since these could be related functions and be inseparate records.

Multi-function Global Business Rule Option 2Put 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 orscript that calls the functions and update it. For example, a reference qualifier field which previously saidjavascript:activeOnly() would become javascript:MyUtil.activeOnly().

Page 29: Business rules

Business Rules Best Practices 28

Write Small, Specific Business RulesSmall, specific business rules are easier to debug and maintain than large, complex ones. Rather than creating onebusiness rule that checks and acts upon numerous conditions, create separate business rules for each condition. Theseindividual 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 thefields for a report when the state changes to closed, consider these as two different results to two different conditionsand create two separate business rules. One that triggers an event when the priority is 1 and one that calculates thefields for a report when the state changes to closed.

Use ConditionsThe Condition field on the Business Rule form allows you to create a JavaScript statement for a condition underwhich the business rule should execute. If you add a condition statement to this field, ServiceNow evaluates thecondition separately and parses the script only if the condition is true, thus improving performance. It is easier todebug 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 thecondition is not met.

Page 30: Business rules

Business Rules Best Practices 29

Use Business Rules to Double-Check Critical InputIf you use a client script to validate data or a reference qualifier to present a filtered list, data may change betweenthe time the user fills in the fields and the time the user submits the form. This mismatch can cause a conflict orerror. 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 selectcurrently available items. If two people fill out a particular form at once and select the same item, the item appears tobe available to both people because neither of them has submitted the form yet. If there is no business rule todouble-check availability, ServiceNow assigns the same item to both requests. By using a business rule to re-verifyitem availability when the form is submitted, the second person receives a warning or other notification indicatingthe 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';

}

}

Page 31: Business rules

Accessing the Workflow Scratchpad from Business Rules 30

Accessing the Workflow Scratchpad fromBusiness Rules

Functionality described here requires the Admin role.

Name: Access Workflow Scratchpad from Business RulesType: Business RuleTable: sc_req_item (Requested Item)Description: A catalog item has been requested, the attached workflow contains a run script activity that populates avalue in the scratchpad. From a business rule running on the requested item, we want to retrieve or set scratchpadvalues.Parameters: n/aScript:

//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();

}

Page 32: Business rules

Building an OR Query in a Business Rule 31

Building an OR Query in a Business Rule

OverviewAn OR condition can be added to any query part within a business rule using the addOrCondition() method.

Example 1Here 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 2A 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

}

Page 33: Business rules

Article Sources and Contributors 32

Article Sources and ContributorsBusiness 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

Page 34: Business rules

Image Sources, Licenses and Contributors 33

Image Sources, Licenses and ContributorsImage:Business_rules_flow.jpg  Source: http://wiki.servicenow.com/index.php?title=File:Business_rules_flow.jpg  License: unknown  Contributors: John.robertsImage:Business_Rule.png  Source: http://wiki.servicenow.com/index.php?title=File:Business_Rule.png  License: unknown  Contributors: Steve.woodImage:Warning.gif  Source: http://wiki.servicenow.com/index.php?title=File:Warning.gif  License: unknown  Contributors: CapaJCImage:Global-Business-Rule-u_ciRefQual.png  Source: http://wiki.servicenow.com/index.php?title=File:Global-Business-Rule-u_ciRefQual.png  License: unknown  Contributors:Chuck.tomasiImage:Script-Include-u_ciRefQual.png  Source: http://wiki.servicenow.com/index.php?title=File:Script-Include-u_ciRefQual.png  License: unknown  Contributors: Chuck.tomasiImage:BR-No-Condition.jpg  Source: http://wiki.servicenow.com/index.php?title=File:BR-No-Condition.jpg  License: unknown  Contributors: Chuck.tomasiImage:BR-Condition.jpg  Source: http://wiki.servicenow.com/index.php?title=File:BR-Condition.jpg  License: unknown  Contributors: Chuck.tomasiImage:Role.gif  Source: http://wiki.servicenow.com/index.php?title=File:Role.gif  License: unknown  Contributors: CapaJC