Business Rule for adding / removing 'xxx' role to assigned_to user

Alberto Consonn
ServiceNow Employee
ServiceNow Employee

Hi all,

I have the following requirements: 

  • If a new Incident will be "assigned to" a user that do not have a certain role "test", add the role automatically to the "assigned to" user
  • If an incident will be set in state Closed, remove automatically the role "test" to the "assigned to" user.

Could you please help me to do that? I was thinking to do it with a AFTER Business Rule.

Please any help are more than welcome!!!

Cheers

Alberto

1 ACCEPTED SOLUTION

Hi Alberto,

Just checked the API and hasRole is a glidesystem or glideuser method so we can't use it the way i've suggested! However, it's just occurred to me that you don't actually need it, the glide query on it's own will determine if the user has the role, if they don't it won't do anything, if they do it will delete it.

var gr = new GlideRecord('sys_user_has_role');
gr.addQuery('user', current.assigned_to);
gr.addQuery('role', '282bf1fac6112285017366cb5f867469');
gr.query();
if(gr.next()){
gr.deleteRecord();
}

This does mean that the code that is adding the role isn't actually working properly though. You should change it to the below:

var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('user', current.assigned_to);
gr.addQuery('role', '282bf1fac6112285017366cb5f867469');
if(!gr.hasNext()){
gr.initialize();
gr.user = current.assigned_to;
gr.role = '282bf1fac6112285017366cb5f867469';
gr.insert();
}

View solution in original post

12 REPLIES 12

Alberto Consonn
ServiceNow Employee
ServiceNow Employee

Ciao Dave,

now it works fine.

Just a small mistake in the second script, so the right script is the following:

var gr = new GlideRecord('sys_user_has_role');
	gr.addQuery('user', current.assigned_to);
	gr.addQuery('role', '282bf1fac6112285017366cb5f867469');
	if(!gr.hasNext()){
		gr.initialize();
		gr.user = current.assigned_to;
		gr.role = '282bf1fac6112285017366cb5f867469';
		gr.insert();
	}

Thanks a lot for your support 🙂

Cheers

Alberto

Writing a code is not a issue here, intent of doing it may cause issue.

If you are trying to save licenses here, I would suggest get in touch with account manager and discuss around the requirement and get inputs from there. 

I totally agree. This isn't really the best practice of how to handle roles either. Since you shouldn't be assigning role directly to a user. Doing it the correct way with groups will allow to do it without any scripting.

 

//Göran