How can I auto populate 'street', 'city', 'state', 'zip' on a record producer from a referenced location?

Scott Raymond2
Tera Contributor

I have a variable on a catalog item, 'location_name_ref', that is a reference to the cmn_location table. I have a single line text variable, 'site_address'. I believe an onChange script is needed to pull the 'street', 'city', 'state', 'zip' label display values from the 'location_name_ref' selection to the 'site_address' variable, but I'm not sure what that code looks like. We have something similar from a previous employee that pulls a user's email from a different reference variable to a single line text variable:

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


if(!isLoading && oldValue != newValue){


g_form.getReference('tech_contact_ref', getUserInfo);


}


}


function getUserInfo(userInfo){

g_form.setValue('technical_contact_email',userInfo.email);

 }

 

For clarity, I would like to select ABC as the referenced location and have it auto populate the street, city, state, and zip from that location in another variable.

1 ACCEPTED SOLUTION

Community Alums
Not applicable

Hi Scott,

 

Try the below onChange client script on 'location_name_ref' variable.

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

	//Type appropriate comment here, and begin script below
	if(newValue == ''){
		g_form.clearValue('site_address');
	}else{
		var location = g_form.getReference('location_name_ref', callBack);
	}
}
function callBack(location){
	var site = location.street;
	var city = location.city;
	var state = location.state;
	var zip = location.zip;
	var address = site+"\n"+city+"\n"+state+"\n"+zip;
	
	g_form.setValue('site_address', address);
}

View solution in original post

6 REPLIES 6

Mike Patel
Tera Sage

you have to create Client Script and Script Includes like I mentioned here

https://community.servicenow.com/community?id=community_article&sys_id=67cdfcd3db4c985c2be0a851ca961...

Community Alums
Not applicable

Hi Scott,

 

Try the below onChange client script on 'location_name_ref' variable.

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

	//Type appropriate comment here, and begin script below
	if(newValue == ''){
		g_form.clearValue('site_address');
	}else{
		var location = g_form.getReference('location_name_ref', callBack);
	}
}
function callBack(location){
	var site = location.street;
	var city = location.city;
	var state = location.state;
	var zip = location.zip;
	var address = site+"\n"+city+"\n"+state+"\n"+zip;
	
	g_form.setValue('site_address', address);
}

This worked perfectly, thank you so much. 

Best practice is to use to GlideAJAX instead of getReference. getReference gets all the fields from the table which takes lot longer then GlideAJAX which gets only specific fields which is much faster.