Auto assign role to Managers in sys_user table

vidhya_mouli
Giga Sage

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

 

4 REPLIES 4

Allen Andreas
Administrator
Administrator

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!

Thank you for your help. However, instead of hard coding sys_id, i used the following code.

userRole.role.setDisplayValue("emp_manager");

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

Can you show me how that can be done? I am new to scripting and trying to figure out things.