The CreatorCon Call for Content is officially open! Get started here.

Query user role in advanced user criteria

Santiago Ruales
Tera Contributor

Hi experts, 

 

Please help. I need to validate, in an advanced user criterion (script), that the user has role knowledge and their manager has the title of IT Manager. I've tried this code, but it doesn't work. Any recommendations, please?

 

(function() {
    var user = new GlideRecord('sys_user');
    if (user.get(user_id)) {
var rol = false;
var gr = new GlideRecord("sys_user_has_role");
gr.addQuery("role", "xxxxda36c0a8016b888c7f06a1ce7e14"); //sys id knowledge role
gr.addQuery("user", user_id);
gr.query();
if (gr.next()) {
rol = true;
}
if (rol){
if (user.manager) { // Check if the user has a manager
var managerSysId = user.manager.title.toString();
if(managerSysId == 'IT Manager'){
answer=true;
}
else{
answer = false;
}
}
}
})();
9 REPLIES 9

RaghavSh
Kilo Patron

@Santiago Ruales Your code seems correct, it worked in background script on my PDI. The only issue could be answer false in the else condition. It only gets evaluated for the last if condition. 

 

Try this:

(function() {
answer = false;
   var user = new GlideRecord('sys_user');
    if (user.get(user_id)) {
var rol = false;
var gr = new GlideRecord("sys_user_has_role");
gr.addQuery("role", "xxxxda36c0a8016b888c7f06a1ce7e14"); //sys id knowledge role
gr.addQuery("user", user_id);
gr.query();
if (gr.next()) {
rol = true;
}
if (rol){
if (user.manager) { // Check if the user has a manager
var managerSysId = user.manager.title.toString();
if(managerSysId == 'IT Manager'){
answer=true;
}
else{
answer = false;
}
}
} 
}
})();

 

Also, avoid using gr as variable, it is not recommended.


Raghav
MVP 2023
LinkedIn

Hi @RaghavSh , I tried your recommendation, but it doesn't work. For some reason, it doesn't validate the role condition.

@Santiago Ruales Try background script, I tried and it worked for me.

 

Make sure the sys_id of the role is correct.


Raghav
MVP 2023
LinkedIn

Rafael Batistot
Kilo Patron

Hi @Santiago Ruales 

 

In Advanced User Criteria scripts, you must return answer = true/false.

user.manager is a reference field — you need to getRefRecord() to access the manager’s fields (like title).

No need to overcomplicate role validation — you can use gs.hasRole('knowledge') (simpler) or query sys_user_has_role.

Always handle the case when a user has no manager.