Auto assign role to Managers in sys_user table
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 06:58 AM
Whenever we choose a user as manager in sys_user table, that manager should automatically get emp_manager role. I wrote the following code:
(function executeRule(current, previous /*null when async*/) {
// Check if the manager field has been updated
if (current.manager) {
// Get the user record for the manager
var managerGr = new GlideRecord('sys_user');
if (managerGr.get(current.manager)) {
// Check if the manager doesn't already have the emp_manager role
var roles = new GlideRecord('sys_user_has_role');
roles.addQuery('user', managerGr.sys_id);
roles.addQuery('role', '=', 'emp_manager');
roles.query();
if (!roles.next()) {
// Assign the emp_manager role to the manager
var userRole = new GlideRecord('sys_user_has_role');
userRole.initialize();
userRole.user = managerGr.sys_id;
userRole.role = 'emp_manager';
userRole.insert();
}
}
}
})(current, previous);
The script runs but it adds a non-existing role (attached images for reference).
I have already created the role emp_manager.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 07:01 AM - edited 03-09-2023 07:02 AM
Hi,
That's because the role field on this record is a reference field and thus you'd need to use the sys_id of the role instead.
You can navigate to list view of your roles in the platform, find the emp_manager role record, right click on it and choose "copy sys_id" and go from there 🙂
Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-09-2023 11:52 PM
Thank you for your help. However, instead of hard coding sys_id, i used the following code.
userRole.role.setDisplayValue("emp_manager");
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-10-2023 12:07 AM
Hi @vidhya_mouli ,
Better approach is to store the sys_id in system property and then use that system property here. So that it will not be hardcoding.
Please Mark My Response as Correct/Helpful based on Impact
Regards,
Gunjan Kiratkar
2X ServiceNow MVP
Community Rising Star 2022
Youtube : ServiceNow Guy
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-10-2023 12:10 AM - edited 03-10-2023 12:11 AM
Can you show me how that can be done? I am new to scripting and trying to figure out things.