get user role in UI Page

davilu
Mega Sage

Hi, I'm trying to create a UI page that has certain fields readonly based on role.   I have the following code in my client script, but I'm getting errors in my console saying gs is not defined and   $(...).ready is not a function.   Can someone help me debug this?   Am I even on the right track?

var roles = [];

var gr = new GlideRecord('sys_user_has_role');  

gr.addQuery('user', gs.getUserID()) ;  

gr.query();  

while(gr.next()) {  

roles.push({

role : gr.getDisplayValue('role') //Will give the sys_id of the roles  

});

}

if (roles.indexOf('admin')) {

document.getElementById('signature').readonly = true;

document.getElementById('signature').style.backgroundColor   = '#ddd';

}

20 REPLIES 20

fredflintstone
Kilo Expert

GlideSystem is not available client side.   You can refer to the client-side API documentation here: https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=client



What you should be using is the GlideUser API.   It has a method available called "hasRole" which returns true/false indicating whether the logged in user has the specified role.   So rather than performing a GlideRecord query client-side and building an array of all the roles the user has (which is woeful in terms of performance, btw) you could do something like:



if (g_user.hasRole('admin')) {


      document.getElementById('signature').readonly = true;


      document.getElementById('signature').style.backgroundColor   = '#ddd';


}



[side note: it's also bad practice to do DOM manipulation, but that's another topic]


Hi fredflintstone, I tried the snippet of code above but still get the same two errors in my console.   Can g_user be used in an UI page?



Additionally, you mentioned performance, what is the best practice for doing a query like this in an UI Page?   Thanks!


davilu
Mega Sage

neither gs.hasRole('admin') or g_user.hasRole('admin') are defined in my console.   I'm also still getting the $(...).ready is not a function error as well.   How do you query a user's roles in a UI Page?


I just tried using g_user in a UI Page client script and did not get any errors.   It is not available in the Developer console in your browser, but it is available inside a client script field in a ServiceNow instance.  



The "$(...)" error sounds unrelated to using g_user.   That seems like an error you're getting due to DOM manipulation so I would recommend against doing that.


hm so strange that the following JS isn't working:



if (g_user.hasRole('admin')) {


      document.getElementById('signature').readonly = true;


      document.getElementById('signature').style.backgroundColor   = '#ddd';


}



Do I have to enclose it in an onLoad function?   Do onLoad functions work in UI Pages?