Get a first look at what's coming. The Developer Passport Australia Release Preview kicks off March 12. Dive in! 

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

Raghav Sharma24
Giga 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.

Hi @Raghav Sharma24 , 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.

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.

 

If you found this response helpful, please mark it as Helpful. If it fully answered your question, consider marking it as Correct. Doing so helps other users find accurate and useful information more easily.