Get lookup value from other entity and set it on the form using Web API in Microsoft Dynamics CRM 2016

In this blog i am going to show you , how you can retrieve a lookup value from other entity in CRM 2016 using web api and set it on the form.

we know how its done in Odata but its time for some Web API action.

let see how its done here 🙂

function yourFunctionName() {

var lookup= Xrm.Page.getAttribute("fieldname").getValue();  //you will get the id with exxtra double quotes or square brackets by doing get value hence you to make it readable by CRM , you must slice it. i have use the below method:
var newid = lookup[0].id.slice(1, -1);  // you will get perfect id like "EDCJDKDJDKJDJDKJDJKD" here.
var req = new XMLHttpRequest(); //once you have the id , you have frame to make a webapi GET call by proving the newid we got.

req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/entitypluralname(" + newid + ")?$select=_prefix_fieldname_value", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(this.response); // you will get the retrieved value in object we stored in result var.
var retrivedvalue= result._prefix_fieldname_value; //get the id of the field
var retrivedformatedvalue= result["_prefix_fieldname_value@OData.Community.Display.V1.FormattedValue"]; //get the formatted name of the field
if (retrivedvalue!= null) {
var value = new Array();
value[0] = new Object();
value[0].id = retrivedvalue;
value[0].name = retrivedformatedvalue;
value[0].entityType = "entityname";
Xrm.Page.getAttribute("fieldname").setValue(value); //set the lookup value finally
}
else
alert("some textt!!!!!!") // optional
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();

you can call this function on change of the field.

i hope this helps!!  🙂

cheers

3 thoughts on “Get lookup value from other entity and set it on the form using Web API in Microsoft Dynamics CRM 2016

  1. Pingback: How to use JavaScript to fill parent lookup on form in Dynamics 365 CRM on-premise? - Tutorial Guruji

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.