JavaScript to get/set the lookup value in Dynamics 365.

Spread the Knowledge...

JavaScript to get/set Lookup field data in Dynamics 365

Let’s discuss about the Lookup field in Dynamics 365 in this blog.

Lookup field is little different than the normal fields available in Dynamics 365 CRM. This field is basically of type EntityReference like we generally have array.

This EntityReference type is the combination of three values i.e. Recordid, RecordName and  EntitySchemaName.

When user create a new lookup field in any entity, then the system will create a N:1 relationship with the other entity.

1. Get Lookup Field Data in Dynamics 365

The below method can be used to get the lookup values along with its Recordid, RecordName and EntitySchemaName. In this example, we will retrieve the data from account lookup.

function GetLookupValue() { 
var lookupObject = Xrm.Page.getAttribute("accountid"); //get the Lookup Object 
if (lookupObject != null) { 
var lookupObjectValues = lookupObject.getValue();//get the Lookup Value 
if (lookupObjectValues != null) 
var Recordid = lookupObjectValues[0].id; //get the Lookup id 
var RecordName = lookupObjectValues[0].name; //get the Lookup Name 
var EntitySchemaName = lookupObjectValues[0].entityType; //get the Lookup EntityName 


2. Set Lookup Field Data in Dynamics 365

As we have discussed above, the lookup field is the combination of three value. i.e Recordid, RecordName and EntitySchemaName.

So to set the lookup field, we have to create a object with these three values. The below method can be used to set the value in the lookup field. 

function SetLookupValue(fieldName, recordId, recordName, entitySchemaName) 
	if(fieldName != null)
		var lookupValue = new Array();
		lookupValue[0] = new Object();
		lookupValue[0].id = recordId;
		lookupValue[0].name = recordName;
		lookupValue[0].entityType = entitySchemaName;




Hope this helps…

Spread the Knowledge...