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

Inactive_Us1976
Giga Expert

Wonderful!   This absolutely resolved an issue I was having calling both an element from the sys_user table and ensuring the script only ran if the record pulled in from the sys_user table did not have an itil role.



Thank you thank you thank you!


palmen
Tera Guru

Thanks for the script, helped me solve assigning a group to a user if the user doesn't have a specific role.


randrews
Tera Guru

not to lob a monkey wrench in your system.. but couldn't you use



gs.getUser(current.opened_by).hasRole()


or getUserByID ??




haven't tried it but it seems like either options SHOULD work.


Just tried it but can't get it to work, I'll stick to the solution posted in the opening post.