Tag a role to an Assignment Group

sachinhs
Tera Contributor

Folks,

Need your help on how to add/append a Role to an Assignment group via script.

On a custom module, user will select a Role (Choice) and Group (Reference), once saved I want to add that role into the group, so that everyone under that Group will inherit the Role.

 

Kindly suggest.

8 REPLIES 8

Ankur Bawiskar
Tera Patron
Tera Patron

@sachinhs 

please share screenshot how user will select role and group?

Sample script, ensure the choice value for the role is the actual role sysId

try {
    var groupRoleRec = new GlideRecord('sys_group_has_role');
    groupRoleRec.initialize();
    groupRoleRec.setValue('group', current.groupField);
    groupRoleRec.setValue('role', current.roleField);
    groupRoleRec.insert();
} catch (ex) {
    gs.info(ex);
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@sachinhs 

Hope you are doing good.

Did my reply answer your question?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@sachinhs 

Hope you are doing good.

Did my reply answer your question?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Runjay Patel
Giga Sage

Hi @sachinhs ,

 

You write after business rule with when to run condition like Role and Group is not empty and use below script.

(function executeRule(current, previous /*null when async*/) {

    var roleSysId = current.u_role; // Replace with actual filed name
    var groupSysId = current.u_group; // Replace with actual filed name

    var gr= new GlideRecord('sys_group_has_role');
    gr.addQuery('group', groupSysId);
    gr.addQuery('role', roleSysId);
    gr.query();

    if (!gr.next()) {
        var newGroupRole = new GlideRecord('sys_group_has_role');
        newGroupRole.initialize();
        newGroupRole.group = groupSysId;
        newGroupRole.role = roleSysId;
        newGroupRole.insert();
    }
})(current, previous);

 

 

-------------------------------------------------------------------------

If you found my response helpful, please consider selecting "Accept as Solution" and marking it as "Helpful." This not only supports me but also benefits the community.


Regards
Runjay Patel - ServiceNow Solution Architect
YouTube: https://www.youtube.com/@RunjayP
LinkedIn: https://www.linkedin.com/in/runjay

-------------------------------------------------------------------------