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.
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 –
Key Poitns-
- 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
- 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
- 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!
Reblogged this on Microsoft Dynamics 365 CRM.
LikeLike