Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

User Has Role?

Chuck Tomasi
Tera Patron

I was writing a business rule to add a third party to the watch list of a task generated from a service catalog request item. "Simple", I said. Then I realized how many tickets our service desk agents open and I'm sure they don't want to be on the watch list for each one. I thought this was the answer:



if (current.request_item.request.opened_by.hasRole('itil')) ...


But Don Goodliffe told me that hasRole() only works on a gs (GlideSession) object (aka currently logged in user). Instead, to get my hands on someone already assigned to a field like opened_by, I would need to query in the sys_user_has_role table for the right info. He was also kind enough to provide me with a function. As a result, here is what I ultimately came up with for my business rule (run on sc_task as a BEFORE rule.)



function userHasRole(userID, role) {
var uhrRec = new GlideRecord('sys_user_has_role');

uhrRec.addQuery('user', userID);
uhrRec.addQuery('role.name', role);
uhrRec.query();
return uhrRec.hasNext();
}

var openedBy = current.request_item.request.opened_by;

if (!userHasRole(openedBy, 'itil')) {
var wList = current.watch_list;

wList = wList + "," + openedBy.name;
current.watch_list = wList;
}

13 REPLIES 13

sylvain_hauser
Tera Contributor

Thanks!

The userHasRole function works great!!!


Thanks for sharing, just used this post today to do something similar.


bburdick
Mega Guru

I spent an hour trying to figure out why hasRole was not working in a workflow script I created. I kept thinking something was wrong with why it couldn't see that the person had the role.

Thanks for this little tidbit!


Blair5
Tera Guru

Chuck,

I'm trying to see if the users in a group have a role. Is this the route I could take to achieve this or would you recommend something else? I've been trying to do this via an onChange client script, but I'm just not able to do it. Any advice is appreciated.

Thank you.