Set and Retrieve a Lookup Id and Value using Xrm.WebApi

We can use JavaScript to connect to Dynamics 365 and set and retrieve a lookup id and value.

Let’s say on an Account, we have the Owner field, which is a lookup:

We would like to set the value of this lookup field through JavaScript. Let’s say we want to set it to another system user, Alan Steiner. To set the value, we will need to know Guid of Alan’s record, and the name of the record. We already know the name is Alan, but let’s retrieve it anyway through code, as we may need this in other scenarios.

We will run this on changing of the website field, just to invoke our code. The code below will grab the owner of 3M accounts:

In previous releases of the Web Api, we would need to pass (“Prefer”, “odata.include-annotations=OData.Community.Display.V1.FormattedValue”) in our request header in order to get the value of the lookup and not just the Id. This is not required when using the Xrm.WebApi.

Setting the Field

Now let’s set the value of the owner field by creating a new array.

In the above example we could do something like this, using the FormattedValue and other fields: