How do I use an Onchange to insert the value of a reference field from the table I'm querying

kenmoulden
Kilo Contributor

Hi all,

                    I'm relatively new to servicenow and javascript, any help would be amazing.   I'm making a service catalog form and I'd like to populate a bunch of fields based on the input from a reference field (server table).   However, 2 of the fields in the server record are reference fields, and my script is returning the sys_id and not the value of the field.

Example:

function onChange(control, oldValue, newValue, isLoading) {

    if (isLoading || newValue == '') {

          return;

    }

var server = new GlideRecord('cmdb_ci_server');

              server.addQuery('sys_id', newValue);

                  server.query();

                  if(server.next()){

var cpu = server.cpu_count;

              var ip = server.ip_address;

var drive = server.u_disk_volumes;

var ram = server.u_ram__gb_;

var assgn_to = server.assigned_to;

var owner = server.owned_by;

                                                         

                g_form.setValue('cpu_count_ken', cpu);

                g_form.setValue('server_ip_address', ip);

g_form.setValue('disk_drives', drive);

g_form.setValue('server_ram', ram);

g_form.setValue('it_owner', assgn_to);

g_form.setValue('business_owner', owner);

}

 

}

The bolded items are returning the sys_id and not the value I'm looking for

Can someone help a newbie out?

6 REPLIES 6

Shishir Srivast
Mega Sage

Hi Ken,



I believe you can do using getReference() on your client script. Please check if below script works. I tried on my incident page and i was able to set the caller value. Hope this should work on your catalog page too.



function onChange(control, oldValue, newValue, isLoading) {


if (isLoading || newValue == '') {


return;


}


var ci = g_form.getReference('cmdb_ci', doAlert);


function doAlert(ci) {


g_form.setValue('cpu_count_ken', ci.cpu_count);


g_form.setValue('server_ip_address', ci.ip_address);


g_form.setValue('disk_drives', ci.u_disk_volumes);


g_form.setValue('server_ram', ci.u_ram__gb_);


g_form.setValue('it_owner', ci.assigned_to);


g_form.setValue('business_owner', ci.owned_by);


}


}


Kalaiarasan Pus
Giga Sage

What people are suggesting here is the regular way of doing this and is time consuming overtime. I would advise you to instead evaluate this utility on share site by michael.ritchie and add it to your instance. It is super useful and such tasks can be done in minutes.



Utility: ServiceNow Share



Documentation: getReferenceAdvanced, g_form.getReference and GlideAjax Alternatives