Skip to content

Dynamic business rule to update user roles based on department changes #1108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
(function executeRule(current, previous /*null when async*/) {

var newDepartment = current.department.getDisplayValue();

// Clear existing roles
var roleGR = new GlideRecord('sys_user_has_role');
roleGR.addQuery('user', current.sys_id);
roleGR.deleteMultiple(); // Remove existing roles

// Assign new roles based on the new department
var newRoleGR = new GlideRecord('sys_role');
newRoleGR.addQuery('name', 'LIKE', newDepartment); // Assuming role names follow department names
newRoleGR.query();

while (newRoleGR.next()) {
var userRoleGR = new GlideRecord('sys_user_has_role');
userRoleGR.initialize();
userRoleGR.user = current.sys_id;
userRoleGR.role = newRoleGR.sys_id;
userRoleGR.insert();
}

gs.info('Updated roles for user ' + current.user_name + ' based on new department: ' + newDepartment);
}
})(current, previous);
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
**Purpose**

This business rule automatically updates user roles in ServiceNow whenever a user's department changes. By ensuring that users have the appropriate roles based on their current department, the rule helps maintain data integrity and enhances access control within the organization.



**Complete Business Rule Configuration**

**Name**: "Update User Roles Based on Department Changes"

**Table**: sys_user

**When**: Before

**Insert**: Checked

**Update**: Checked


**Condition**:

**javascript**

'''current.department.changes();'''
Loading