I want to load the user name of a reference variable into the another variable

Bret Smith
Giga Guru

 

I want to load the user name of a reference variable into the another variable 

it_director_business_app (user selected from sys_user table)

it_director (to be used to send an notification)

 

 

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
var itdirector = g_form.getDisplayValue('it_director_business_app');
   //Type appropriate comment here, and begin script below
   g_form.setValue('it_director',itdirector);
}
9 REPLIES 9

Brad Bowman
Kilo Patron
Kilo Patron

You would have to use getReference with a callback or a GlideAjax call to a script include

https://www.servicenow.com/community/developer-articles/glideajax-example-cheat-sheet-updated/ta-p/2... 

Colin Doyle
Tera Contributor

You can possibly have the field be dependent on that reference field. 
Or you can have the field dot-walk to the reference record.

 

Did this for a project I was on where, in form builder, you can add a field for [reference_field].[field]

ColinDoyle_0-1725982375707.png

This will work like an onchance client script but do the ajax work for you

Sid_Takali
Kilo Patron
Kilo Patron

Hi @Bret Smith Try calling script include from onChange Client script on IT Director Business App field.

Script Include : getUserName

var GetUserName = Class.create();
GetUserName.prototype = {
    initialize: function() {},
    
    getUserNameById: function(userId) {
        var userGr = new GlideRecord('sys_user');
        if (userGr.get(userId)) {
            return userGr.name; // or userGr.user_name depending on your needs
        }
        return '';
    }
};

 

onChange Client Script : 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var ga = new GlideAjax('GetUserName');
    ga.addParam('sys_id', newValue);
    ga.getXMLAnswer(function(response) {
        var username = response;
        g_form.setValue('it_director', username);
    });
}

 

 

 

I still get a blank variable on my form

 

 

Script Include

GetITDirectorName

 

BretSmith_0-1725985977975.png

 

 

 
var GetITDirectorName = Class.create();
GetITDirectorName.prototype = {
    initialize: function() {
    },
   
    GetITDirectorNameById: function(userId) {
        var userGr = new GlideRecord('sys_user');
        if (userGr.get(userId)) {
            return userGr.name; // or userGr.user_name depending on your needs
        }
        return '';
    }
};
 
 Client Script 
onchange
BretSmith_1-1725987126712.png
function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var ga = new GlideAjax('GetITDirectorName');
    ga.addParam('sys_id', newValue);
    ga.getXMLAnswer(function(response) {
        var username = response;
        g_form.setValue('it_director', username);
    }
    );
}