Get and Set Lookup field value in Dynamics 365
2 min readJun 17, 2022
There may be cases where you need to set or get lookup field value.
What is Lookup field?
A Lookup field represents an association with the entity. It can be the same entity.
Setting lookup field value its not simple way you have to set three parameters to set the lookup value those are follows –
- GUID of the lookup record
- Name of the lookup record
- Entity Name of the lookup which entity the lookup record is belongs to.
Here is sample code how to set the lookup value using JavaScript Dynamics CRM.
JavaScript Code: Getting Lookup
// Get Lookup// Getting Form Context
var formContext = executionContext.getFormContext();
// Getting the value of Lookup
var LookupId = formContext.getAttribute("new_lookup").getValue();
// Getting the GUID of the lookup record
var Id = LookupId[0].id;// Getting Name of the lookup record
Id = Id.replace(",", "").replace("}", "").replace("{","");var Name = LookupId[0].name;
// Getting Entity Name of the lookup which entity, the lookup record is belonging to.
var EntityType = LookupId[0].entityType;
JavaScript Code: Setting Lookup
// Set Lookupvar lookup = []; // Creating a new lookup Array
lookup[0] = {}; // new Object
lookup[0].id = Id; // GUID of the lookup id
lookup[0].name = Name; // Name of the lookup
lookup[0].entityType = EntityType; // Entity Type of the lookup entity
var OtherLookup= formContext.getAttribute("new_Otherl").setValue(lookup);
JavaScript Function:
function get_set_LookupValue(executionContext)
{try {// Get Lookup// Getting Form Context
var formContext = executionContext.getFormContext();
// Getting the value of Lookup
var LookupId = formContext.getAttribute("new_lookup").getValue();
// Getting the GUID of the lookup record
var Id = LookupId[0].id;// Getting Name of the lookup record
Id = Id.replace(",", "").replace("}", "").replace("{","");var Name = LookupId[0].name;
// Getting Entity Name of the lookup which entity, the lookup record is belonging to.
var EntityType = LookupId[0].entityType;// Set Lookupvar lookup = []; // Creating a new lookup Array
lookup[0] = {}; // new Object
lookup[0].id = Id; // GUID of the lookup id
lookup[0].name = Name; // Name of the lookup
lookup[0].entityType = EntityType; // Entity Type of the lookup entity
var OtherLookup= formContext.getAttribute("new_Otherl").setValue(lookup);
} catch (ex) {
console.log("getLookupValue: Error -> " + ex.message);
}
}