Dynamics 365 WEB API · Dynamics CRM Javascript · Javascript

Dynamics 365 CRM Auto Populate lookup field

One of the community forum requirement was to auto populate lookup field B based on value of Lookup field A.

Scenario

Field a: lookup field

Field b: lookup field

Based on lookup field a . value should autopopulate in lookup field b .

Solution –

I have added two lookup State and City on Account form. City has lookup of State. I have also added OOB record filtering settings to show city which belogns to selected state only.

lookup01

Created sample data in state and city for thise use case. This logic/code can be applied to any requirement to auto populate lookup second lookup field based on first lookup field value. For this blog I have chosen city & state.

Javascript Code


function fillLookup(executionContext)
{
  var formContext = executionContext.getFormContext();

  var lookup = formContext.getAttribute("new_state").getValue();
  if (lookup != null) 
  {
	var lookunfieldStateId=lookup[0].id;
	Xrm.WebApi.online.retrieveMultipleRecords("new_city", "?$select=new_name&$filter=_new_state_value eq "+lookunfieldStateId+"&$orderby=createdon desc&$top=1").then(
    function success(results) {
        for (var i = 0; i < results.entities.length; i++) {
            var new_name = results.entities[i]["new_name"];
			var new_cityid = results.entities[i]["new_cityid"];
			var value = new Array(); //create a new object array
			value[0] = new Object();
			value[0].id = new_cityid; // set ID to ID
			value[0].name = new_name; //set name to name
			value[0].entityType = "new_city"; //optional
			formContext.getAttribute("new_city").setValue(value);
        }
    },
    function(error) {
        Xrm.Utility.alertDialog(error.message);
    }
);
  }
}

Result –

lookup03

 

Key Poitns-

  1. In a single post I have covered topic on how to get lookup field value, how to set another lookup field value & how to apply related record filtering
  2. I have used order by based on created on and applied Top 1 to get first record but it can be changed based on your requirement
  3. We could also disable disable lookuo to be only auto populated by the system and not let user enter value in it

Hope this helps!

3 thoughts on “Dynamics 365 CRM Auto Populate lookup field

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s