How to auto populate current logged in user department in service catalog variables

devipriya
Giga Contributor
 
4 REPLIES 4

Vishal Birajdar
Giga Sage


Hello Devipriya 

Assuming,

1.You don't have any requested for reference variable on catalog item (If you have then you can use OnChange client script)

2.You have Department variable on catalog item referencing to Department table 


Step 1: Write onLoad client script and call script Include to get department of current user

 

function onLoad() {
var userId= g_user.userID; //get current user

var gaUserDetails = new GlideAjax('UserDetails_utils');
gaUserDetails.addParam('sysparm_name','getUserDepartment');
gaUserDetails.addParam('sysparm_user',userId);
gaUserDetails.getXMLAnswer(getDepartment);

function getDepartment(answer){
g_form.setValue('department',answer); //set department value
}

}

 

VishalBirajdar7_0-1676212244645.png

 

Step 2 : Write client callable script include

 

var UserDetails_utils = Class.create();
UserDetails_utils.prototype = Object.extendsObject(AbstractAjaxProcessor, {

getUserDepartment: function() {
var user = this.getParameter('sysparm_user');
var grUser = new GlideRecord('sys_user');
grUser.addQuery('sys_id', user);
grUser.query();
if (grUser.next()) {
gs.log('UserDetails_utils:inside if');
var department = grUser.getValue('department');
gs.log('UserDetails_utils:department' + department);
return department;
}

},


type: 'UserDetails_utils'
});

 

VishalBirajdar7_1-1676212362613.png

 

Note : In script include you can use Glide Session API also to get User

Hope this solution works for you...!!

 

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

Divya Rajasekar
Tera Contributor

Hi,

If you want to get the current logged in user use the default value part of the variable javascript:gs.getUserId().getDisplayValue('department').

If you want to populate when you change user. Create onchange client script on the variable field user name field and create script include to query based on the user name and return and set value of department for the variable.

If you are using Utah version, there is autopopulate section in variable make use of that.

 

Thanks,

Divya Rajasekar

Pooja Mallikarj
Kilo Sage

Hi @devipriya ,

If you want Logged In user 's department ,you can add in the Default Value of Department variable as below.

javascript: gs.getUser().getRecord().getDisplayValue("department")

Thanks,

Pooja M

Riyaz Ali Moham
Mega Guru

Hi @devipriya ,
Use javascript:gs.getUserID().getRecord().getDisplayValue('department'); this code in the "Default Value" section of variable record.