display user name, cost center & country

Anubhav Srivas1
Tera Expert

Hi All,

 

i have a request where based on logged in user i have to fetch details from the user table regarding the following,(on load)

 

cost center

country

user id

 

the value should change if the logged in user "requested for" is changed manually. (on change)

 

need your help.

5 REPLIES 5

kalpesh9
Mega Guru

Hello @Anubhav Srivas1 ,

 

Please follow below article see if it helps,

 

https://www.servicenow.com/community/itsm-articles/ways-to-populate-user-details-in-catalog-using-gl...

 

Thanks,

Kalpesh

 

Mark Correct if this solves your issue and also mark  Helpful if you find my response worthy.

Namrata Ghorpad
Mega Sage
Mega Sage

Hi @Anubhav Srivas1 ,

If you want to auto populate the values of fields cost center, country and user id whenever form loads then use the below script in default values of these fields.

javascript: gs.getUser().getRecord().getValue('country');

javascript: gs.getUserName();

 

Regards,

Namrata

Hi Namrata,

 

I need default value for cost center code, can you please help?

Rahul Mane2
Kilo Guru

Hi Anubhav

Try below codes

 

// OnLoad function to fetch initial details on page load
function onLoad() {
var currentUserID = g_user.userID;

// Query the user table to fetch the details for the logged-in user
var userGr = new GlideRecord('sys_user');
userGr.addQuery('user_name', currentUserID);
userGr.query();

if (userGr.next()) {
// Fetch the cost center, country, and user ID from the user table
var costCenter = userGr.getValue('cost_center');
var country = userGr.getValue('country');
var userID = userGr.getValue('user_name');

// Set the fetched values in the corresponding fields on the form
g_form.setValue('cost_center', costCenter);
g_form.setValue('country', country);
g_form.setValue('user_id', userID);
}
}

 

 

// OnChange function to fetch details when the "requested for" field is changed
function onChangeRequestedFor() {
var requestedFor = g_form.getValue('requested_for');

// Query the user table to fetch the details for the selected "requested for" user
var userGr = new GlideRecord('sys_user');
userGr.addQuery('user_name', requestedFor);
userGr.query();

if (userGr.next()) {
// Fetch the cost center, country, and user ID from the user table
var costCenter = userGr.getValue('cost_center');
var country = userGr.getValue('country');
var userID = userGr.getValue('user_name');

// Set the fetched values in the corresponding fields on the form
g_form.setValue('cost_center', costCenter);
g_form.setValue('country', country);
g_form.setValue('user_id', userID);
}
}