Script to auto populate fields based on chosen asset in Service Catalog

DT
Kilo Contributor

Dear Community Members,

I've been working on a form, where the model name and warranty end date fields are auto populated based on the chosen user and his/hers asset:
find_real_file.png This has been achieved by using reference qualifiers only, because I'm not good in scripting.
Unfortunately, this approach has been rejected by the Project Lead. It has been said that it should be done via a script.
This is the point where my problem starts, because I'm new to ServiceNow and my scripting skills are less than zero.
I've tried to find something on the forum, but it all is pure black magic to me.
Could you please give me a hand with this and suggest any examples or something I could start with, which won't make me confused?

My variable set name is: "pc_replacement"

My variables are:
- "damaged_pc" (table: "alm_hardware", field name: "display_name")

- "model_of_pc" (table: "alm_hardware", field name: "model")

- "warranty_end_date" (table: "alm_hardware", field name: "warranty_expiration")

If there is additional information needed, please let me know!
Thank you in advance!


Regards,
Dawid

1 ACCEPTED SOLUTION

Hi DT,

Hopefully this is the fix.

Clear the label field values on Model of PC field

find_real_file.png

 

Replace scripts:

 

Client script: populateAssetDetails

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
	
	var glide = new GlideAjax('populateAssetInfo');
	glide.addParam('sysparm_name', 'populateAssetDetails');
    glide.addParam('sysparm_damagedpc', g_form.getValue('damaged_pc'));
	glide.getXML(updateFields);

}


function updateFields(response) {
      var answer = response.responseXML.documentElement.getAttribute("answer");
      var clearvalue; // Stays Undefined
      if (answer) {
              var returneddata = JSON.parse(answer);
		  g_form.clearOptions('model_of_pc');
		  g_form.addOption('model_of_pc', returneddata.display_name, returneddata.display_name);
		 g_form.setValue('warranty_end_date', returneddata.warranty);
      } else {
			  g_form.setValue('warranty_end_date', clearvalue);
      }

}

   

Script include: populateAssetInfo

var populateAssetInfo = Class.create();
populateAssetInfo.prototype = Object.extendsObject(AbstractAjaxProcessor, {

	populateAssetDetails: function(){ //function being called asynchronously from client script
		var damagedpc = this.getParameter('sysparm_damagedpc'); //store the forms damaged pc sys id value
		var assetGR = new GlideRecord('alm_hardware'); //open a search on the alm_hardware table
		assetGR.addQuery('sys_id', damagedpc); //filter for a record with sys id of the sys id from before
		assetGR.query(); //look if theres a match
		if(assetGR.next()){ //if there is a match for the sys id
			gs.log('[test] found a match');
			var json = new JSON();
			var assetDetails = { //create a new object to store information
				"model" : assetGR.model.toString(), //store the model of the asset
				"warranty" : assetGR.warranty_expiration.toString(), //store the warranty expiration date
				"display_name" : assetGR.model.display_name.toString()
			};
			gs.log('[test] model: ' + assetGR.model + ' / warranty ' + assetGR.warranty_expiration + ' / display_name: ' + assetGR.model.display_name + ' / ' + assetDetails.display_name);
			return JSON.stringify(assetDetails); //return the object (encoded)
			
		}else{
			return null; //if we didnt find a record, return empty
		}
	},
	
	loadAssetsForUser: function(){
		var impacteduser = this.getParameter('sysparm_impacteduser');
		var assetGR = new GlideRecord('alm_hardware');
		assetGR.addQuery('assigned_to', impacteduser);
		assetGR.query();
		var assetList = [];
		
		while(assetGR.next()){
			var assetObj = {
				"display_name":assetGR.display_name.toString(),
				"sys_id":assetGR.sys_id.toString()
			};
			
			assetList.push(assetObj);
			gs.log('[test] pushing assetGR.display_name: ' + assetGR.display_name);
		}
		return JSON.stringify(assetList);
	},
    type: 'populateAssetInfo'
});

and theres no need to change the other client script

 

 

View solution in original post

23 REPLIES 23

DT
Kilo Contributor

Hi Schloke,

thank you for your input and sorry that I didn't mention it earlier, the variables are Lookup Select Box type as it has been one of the project requirements.

Regards,
Dawid

kay, so I don't think that will make a difference here. You need to follow the same steps as suggested above and in Loop up Select box also there you can add Reference Qualifier as shown below:

find_real_file.png

 

Please try and let me know if you are still facing an issue. I can help further to assist you here.

Hope this helps. Please mark the answer as correct/helpful based on impact.

Regards,
Shloke

Hope this helps. Please mark the answer as correct/helpful based on impact.

Regards,
Shloke

Dan H
Tera Guru

 

Hi @DT

I have figured this out with your constraints. I'll post the most significant changes/things you need to change below.

 

Variable set fields: 

damaged pc: (make sure 'lookup value field', 'lookup label field' match)

find_real_file.png

 

Model of the damaged pc: (make sure 'lookup value field' and 'lookup label fields' match)

find_real_file.png

 

2 Client scripts:

damaged pc client script: (make sure its onChange + on damaged pc variable)

find_real_file.png

 

Script:

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
	
	var glide = new GlideAjax('populateAssetInfo');
	glide.addParam('sysparm_name', 'populateAssetDetails');
    glide.addParam('sysparm_damagedpc', g_form.getValue('damaged_pc'));
	glide.getXML(updateFields);

}


function updateFields(response) {
      var answer = response.responseXML.documentElement.getAttribute("answer");
      var clearvalue; // Stays Undefined
      if (answer) {
              var returneddata = JSON.parse(answer);
		  g_form.setValue('model_of_pc', returneddata.model);
		  g_form.setValue('warranty_end_date', returneddata.warranty);
      } else {
               g_form.setValue('model_of_pc', clearvalue);
			  g_form.setValue('warranty_end_date', clearvalue);
      }

}

   

 

impacted user client script: (make sure its onChange + on impacted user variable)

find_real_file.png

 

Script:

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
	
	
	
	var glide = new GlideAjax('populateAssetInfo');
	glide.addParam('sysparm_name', 'loadAssetsForUser');
    glide.addParam('sysparm_impacteduser', g_form.getValue('impacted_user'));
	glide.getXML(updateFields);

}


function updateFields(response) {
	  g_form.clearOptions('damaged_pc');
	  g_form.clearValue('model_of_pc');
	  g_form.clearValue('warranty_end_date');
      var answer = response.responseXML.documentElement.getAttribute("answer");
      var clearvalue; // Stays Undefined
      if (answer) {
              var returneddata = JSON.parse(answer);
			 for(i = 0; i < returneddata.length; i ++){
				 g_form.addOption('damaged_pc', returneddata[i].sys_id.toString(), returneddata[i].display_name.toString());
			 }
      } else {
             //  g_form.setValue('model_of_pc', clearvalue);
			 // g_form.setValue('warranty_end_date', clearvalue);
      }

}

   

 

Script include (replace the script in the current populateAssetInfo script include):

(Make sure script include is named: populateAssetInfo)

 

var populateAssetInfo = Class.create();
populateAssetInfo.prototype = Object.extendsObject(AbstractAjaxProcessor, {

	populateAssetDetails: function(){ //function being called asynchronously from client script
		gs.log('[test] inside script include: populateAssetInfo -> populateAssetDetails()');
		var damagedpc = this.getParameter('sysparm_damagedpc'); //store the forms damaged pc sys id value
		var assetGR = new GlideRecord('alm_hardware'); //open a search on the alm_hardware table
		gs.log('[test] damagedpc: ' + damagedpc);
		assetGR.addQuery('sys_id', damagedpc); //filter for a record with sys id of the sys id from before
		assetGR.query(); //look if theres a match
		if(assetGR.next()){ //if there is a match for the sys id
			gs.log('[test] found a match');
			var json = new JSON();
			var assetDetails = { //create a new object to store information
				"model" : assetGR.model.toString(), //store the model of the asset
				"warranty" : assetGR.warranty_expiration.toString() //store the warranty expiration date
				};
			gs.log('[test] model: ' + assetGR.model + ' / warranty ' + assetGR.warranty_expiration);
			return JSON.stringify(assetDetails); //return the object (encoded)
			
		}else{
			return null; //if we didnt find a record, return empty
		}
	},
	
	loadAssetsForUser: function(){
		var impacteduser = this.getParameter('sysparm_impacteduser');
		var assetGR = new GlideRecord('alm_hardware');
		assetGR.addQuery('assigned_to', impacteduser);
		assetGR.query();
		var assetList = [];
		
		while(assetGR.next()){
			//assetList.push(assetGR.display_name.toString());
			var assetObj = {
				"display_name":assetGR.display_name.toString(),
				"sys_id":assetGR.sys_id.toString()
			};
			
			assetList.push(assetObj);
			gs.log('[test] pushing assetGR.display_name: ' + assetGR.display_name);
		}
		return JSON.stringify(assetList);
	},
    type: 'populateAssetInfo'
});

 

Outcomes:

Selecting a user populates the Damaged PC lookup select box with their owned assets.

Selecting one of these assets populates the model, date field.

All fields are correct type

Changing a user after it has populated fields will clear the currently populated fields.

find_real_file.png

find_real_file.png

I hope that is straightforward and the implementation works for you.

Let me know if you have any queries.

 

Please mark my answer as Correct/Helpful based on impact

Regards,

Dan H

DT
Kilo Contributor

I'm pretty sure I've followed the instruction, but it seems there is still a bug somewhere.

After choosing the asset, it auto populates with sysID instead of the model name (screenshot below).

Not sure if it helps, but after the daily project call, I've been given the green light to change the field type from Lookup Select Box into Reference type for the model variable only.

 

find_real_file.png

Right click the Model of the Damaged PC field and change the "look up label fields" value. Add the display_name and sys_id and save and reload the item.

Not sure why the sys id is showing if the current value is model. Check if display_name gives the display name and not a sys id and use that field instead.

find_real_file.png

 

As for the Javascript error, you can find online how to open the developer tools/console for your browser and it will show the error.

If you post the error, I'd be able to help fix the issue. As for the green light on the reference field, lets see if this solution works first