Dynamically populate reference field based on another

Chris169
Kilo Contributor

Hi,

I’m new to the scripting side of SN development and I have a requirement to auto populate  field based on a user:

When a user enters a name in the ‘Requested by’ field: 

I want the ‘Department’ field to automatically populate with that users assigned Department which we have referenced in the sys_user table:

 

I’ve tried to piece together what I think I need but it’s not working so not sure where I’m going wrong:

 

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

 

 userObject = g_form.getReference('requested_by');

  

 g_form.setValue('department', userObject.department);

  

}

 

Any help would be greatly appreciated.

Thanks

Chris

1 ACCEPTED SOLUTION

VigneshMC
Mega Sage

Try this

function onChange(control, oldValue, newValue, isLoading) {
   var userObject = g_form.getReference('requested_by', doAlert); // doAlert is our callback function
}
function doAlert(userObject) { //reference is passed into callback as first arguments
   g_form.setValue('department', userObject.department);
}

View solution in original post

4 REPLIES 4

VigneshMC
Mega Sage

Try this

function onChange(control, oldValue, newValue, isLoading) {
   var userObject = g_form.getReference('requested_by', doAlert); // doAlert is our callback function
}
function doAlert(userObject) { //reference is passed into callback as first arguments
   g_form.setValue('department', userObject.department);
}

Chris169
Kilo Contributor

Perfect...thanks.

Jim Coyne
Kilo Patron

You will want to take a look at my response to your other question in order to combine both your requests into 1 Client Script - Dynamically populating reference fields.

Using getReference with a callback function is not really a good idea when you end up populating a reference field because the setValue call forces the platform to go back to the server to get the display name of the department in order to show it in the browser.  So you end up with 2 calls to the server, when 1 call using GlideAjax (described in the other post) can return both the sys_id and display value for the field.  Much more efficient.

Using getReference with a callback function is fine when you are populating other types of fields, like string or choice lists, etc...

Chris169
Kilo Contributor

Thanks for the help on this.

 

C