Servicenow script for change field value based on another field
- User
Servicenow script for change field value based on another field
- Assistant
Servicenow script for change field value based on another field
To change the value of one field based on another field within ServiceNow, you can use Business Rules or Client Scripts depending on whether you want this to occur on the server-side (Business Rule) or client-side (Client Script). Here's a brief overview of both methods:
1. Business Rule (Server-side): A Business Rule runs on the server side, either before or after database operations such as insert, update, or delete. To set the value of a field based on another field when a record is inserted or updated, you can create a Before Business Rule.
Here's a simple example of a Before Business Rule that sets the value of field2 based on field1. Let's assume that if field1 is 'Active', we want to set field2 to 'Enabled'.
(function executeRule(current, previous /*null when async*/) {
// Check the value in 'field1'
if (current.field1 == 'Active') {
// Set 'field2' to 'Enabled'
current.field2 = 'Enabled';
}
})(current, previous);
2. Client Script (Client-side): A Client Script runs on the client side (in the user's browser) and can respond to user actions such as changing the value in a form field. To change the value of a field based on another field's value when a user modifies it, you can use an 'onChange' Client Script.
Here's an example of an 'onChange' Client Script that sets the value of field2 based on field1. Assume that if field1 is 'Active', we want to set field2 to 'Enabled'.
field1 (the one that will trigger the change).function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
// If 'field1' is set to 'Active', set 'field2' to 'Enabled'
if (newValue == 'Active') {
g_form.setValue('field2', 'Enabled');
}
}
Remember to replace field1 and field2 with the actual field names that you want to use in your ServiceNow instance. Make sure to test your script thoroughly to avoid any unwanted behavior.