Check to see if a person in a reference field has a particular role

Tony Capone
Kilo Expert

I have a reference field on a service catalog item that points to the sys_user table. When a person is selected, I want to be able to show/hide another field if that person has a particular role. 

Most solutions I have seen are using "g_user". My understanding is that this only applies to the logged in user. Here is a sample of the proposed solution:

var role_check =   g_user.hasRole('Mention the Role Name');

if(role_check == true){

g_form.setDisplay('Field Name', true);

}

else if(role_check == false){

g_form.setDisplay('Field Name', false);

What can I use instead of g_user? Is there another solution?

2 REPLIES 2

Allen Andreas
Administrator
Administrator

Hello,

You'd want to create an onChange client script to execute on the field where they pick the user. Then use GlideAjax to communicate with the server, passing the selected user value, then query the sys_user_has_role table to see if they have the particular role and then send back to the client true or false. If true, show the field, if false, don't.

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Tony,

Here are the scripts.

Client Script.

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
	var roleName = '<name of role to check>';  // name of role to check
    var ajax = new GlideAjax('UserUtilClient');
    ajax.addParam('sysparm_name', 'hasRole');
    ajax.addParam('sysparm_user_id', newValue);
	ajax.addParam('sysparm_role_name', roleName);
    ajax.getXMLAnswer(function(answer) {
        if (answer == 'true') {  // display or hide other field
            g_form.setDisplay('field_to_hide', true);
        } else {
			g_form.setDisplay('field_to_hide', false);
		}
    });
 }

Script Include

var UserUtilClient = Class.create();
UserUtilClient.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    hasRole: function() {
        var userSysId = this.getParameter('sysparm_user_id');
        var roleName = this.getParameter('sysparm_role_name');
        var grUserRole = new GlideRecord('sys_user_has_role');
        grUserRole.addActiveQuery();
        grUserRole.addQuery('user', userSysId);
        grUserRole.addQuery('role.name', roleName);
        grUserRole.query();
		return grUserRole.hasNext();
    },
    type: 'UserUtilClient'
});

find_real_file.png

Execution sample

case 1: selected user has role. Another field is displayed

find_real_file.png

case 2: selected user do not have role. Another field is not displayed

find_real_file.png