When customizing forms in Dynamics 365 Power Apps, one common requirement is to set lookup field in Dynamics 365 using JavaScript. For example, you may want to automatically populate a related lookup field when another field is selected, such as setting a Contact based on the selected Account. This not only saves time for users but also ensures data consistency across your system.
To set a lookup field to another lookup field on a Dynamics 365 Power Apps form using JavaScript, you need to retrieve the value from one lookup field and then set that value to another lookup field.
Step-by-Step Guide to Set Lookup Field in Dynamics 365 Using JavaScript
Here’s how you can do this:
Set Account Lookup Based on Contact Lookup or GUID
Step 1 : Understand the Dynamic 365 Lookup Field JavaScript Structure
- Id: The Unique GUID of the Record
- name: The Primary Field display on the form
- entityType: The Logical name of the entity (e.g account,contact)
Step 2 : JavaScript Function
you need to create Web resource file add this JS Code in your Web resource
Here is the example code to fetch Account based on contact.
function SetAccountName(executionContext) {
var formContext = executionContext.getFormContext();
var contactID = formContext.data.entity.getId();
if (contactID != null) {
Xrm.WebApi.retrieveMultipleRecords("account", "?$select=" + "accountid" + "&$filter=" + "_primarycontactid_value" + " eq " + contactID).then(
function success(result) {
console.log(result);
if (result.entities.length > 0) {
var account = new Array();
account[0] = new Object();
account[0].entityType = "account";
account[0].id = result.entities[0]["accountid"];
account[0].name = result.entities[0]["accountid@OData.Community.Display.V1.FormattedValue"];
formContext.getAttribute("parentcustomerid").setValue(account);
} else {
formContext.getAttribute("parentcustomerid").setValue();
formContext.getAttribute("parentcustomerid").setValue();
}
},
function(error) {
alert(error.message);
}
);
}
}
Step 3 : Add Javascript to your Form
- Go to Form Customization in D365
- Create a new JavaScript web resource and add the function above
- on the Form register Function on Change event.
How to Set Lookup Field in Dynamics 365 Using JavaScript on Power Apps Forms
