Business rule: add/remove custom role from Manager on group

emmalowey
Tera Contributor

Hello, 

I'm currently working on setting up a business rule for the sys_user_group table, and I could use some guidance. The objective is to automatically assign a custom role to the user who becomes the manager of a group.

 

In the business rule, I want to incorporate logic that checks both the current and previous managers. The reason behind this is to address scenarios where the user who was managing the group gets removed. In such cases, I also want to ensure that the corresponding role is removed from that particular user.

 

I'd appreciate any insights, tips, or sample code snippets that could help me achieve this functionality seamlessly. If anyone has experience with similar scenarios or suggestions on how to structure this business rule effectively, please share your thoughts.

 

Thank you in advance for your assistance!

1 REPLY 1

Brad Bowman
Kilo Patron
Kilo Patron

Hi Emma,

You can accomplish this with a Business Rule running after Update on the sys_user_group table when Manager changes like this:

BradBowman_0-1700663055216.png

The Script on the Advanced tab would look like this to remove the role from the previous manager, where applicable, and add the role to the new manager:

(function executeRule(current, previous /*null when async*/) {
	if (previous.manager != '') {
		var delRole = new GlideRecord('sys_user_has_role');
		delRole.addQuery('user', previous.manager);
		delRole.addQuery('role.name', 'agent_admin'); //your role name or use 'role' and sys_id
		delRole.query();
		if (delRole.next()) {
			delRole.deleteRecord();
		}
	}

	if (current.manager != '') {
		var addRole = new GlideRecord('sys_user_has_role');
		addRole.newRecord();
		addRole.user=current.manager;
		addRole.role='8d1f97f0c611227d0100078c7573be2f'; //sys_id of role
		addRole.insert();	
	}
})(current, previous);