How to set a lookup value in Dynamics 365/ Model Driven apps using javascript

Hello everyone and welcome to my blog. In today’s blog I will show on how to set a lookup field value in Dynamics 365/ Model Driven apps using javascript.

Lookups in Dynamics 365 model driven apps are essentially arrays. Each array object should have the following three properties.

  • entityType : Logical name of the lookup record table
  • id: the guid of the lookup record
  • name: text representing the name of the record to be displayed in the lookup

In my example I want to set the Primary Contact field of account dynamically using script.

And below is the code to do that.

function setLookupValue(e) {
   var formContext = e.getFormContext();

   // create the object
   var primaryContact = {
      "entityType": "contact", // change this to the logical name of parent table.
      "id": "f9aca81b-bc5e-ed11-9562-6045bdad1b49", // guid of the parent record
      "name": "sample contact" // text representing the name of the record to be displayed in the lookup.
   };

   // replace primarycontactid with the lookup field name in your case.
   formContext.getAttribute("primarycontactid").setValue([primaryContact]);
}

As you can see in the above code, I have created an object primaryContact with the three required properties entityType, id and name.

And then set the value of the lookup to an array object. Observe the square brackets I am using while setting the primarycontactid lookup field – [primaryContact]

Please note that you need to change the field names accordingly as per your requirement. Check for the comments in each line of code.

Hope you liked this post. If this post has helped, you can buy me a coffee.

For similar topics on Microsoft.NET and Power Platform, subscribe to my blog using the Subscribe option on right pane.

Debajit Dutta
Business Solutions MVP