Problem to convert sys_id of reference field into string

Matki
Tera Contributor

Hello everyone,

my goal is to display the cost center of the current requested for automatically in the Service Portal.

Therefore, I map the field cost_centers_clock (reference field) with the cost_center field from the user record in a client script:

 

Matki_0-1667553498522.png

How can I convert the sys_id into the name? 

 

My code:

 

function onChange(control, oldValue, newValue, isLoading) {
    if (newValue == '') {
        return;
    }
    var gr = new GlideRecord('sys_user');
    gr.addQuery('sys_id', newValue);
    gr.query(myCallbackFunction);

    function myCallbackFunction(gr) {
        if (gr.next()) {
           g_form.setValue('cost_centers_clock', gr.cost_center);
        }
	}
}

 

I have found several solutions, but they have not worked for me.

 

g_form.setValue('cost_centers_clock', gr.getDispayValue('cost_center'));

g_form.setValue('cost_centers_clock', gr.getDispayValue('cost_center.name'));

gr.cost_centers_clock.getDisplayValue()

// Use of GlideAjax...

 

 

Can anyone help me?
Thanks in advance!

 

 

6 REPLIES 6

Akshay37
Mega Guru

Hi, 

 

Try to use gr.cost_center.getDisplayValue() instead of gr.cost_center 

or my recommendation is to change variable type to reference type.

 

 

Please mark it correct/helpful if this helps you

 

Thanks,

Akshay

MD AQUIB KHAN
Giga Guru
Hi,
Please find the scripts below:

Script Include: 

getcostCenter: function() {

var gruser = this.getParameter('sysparm_user');
var gr = new GlideRecord('sys_user');
gr.addQuery('sys_id', gruser);
gr.query();
if (gr.next()) {
var grcost = gr.getDisplayValue('cost_center');

}

return grcost;
},

 

Client Scripts:

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading) {
return;
}

var gr = new GlideAjax('CostCentre');
gr.addParam('sysparm_name','getcostCenter');
gr.addParam('sysparm_user',newValue);
gr.getXML(callback);

function callback(response){
var answer = response.responseXML.documentElement.getAttribute('answer');
alert(answer);
g_form.setValue('cost',answer); // Please add your backend field name. Note: Here my cost center field type is single Line text 
}

}


Output:

MDAQUIBKHAN_0-1667564662363.png