Get/Set Lookup field value using JavaScript in Dynamics CRM/Dynamics 365 CE

Hi Everyone,

Sometimes, it is really good to keep required and repeated code handy. 

Here is the JavaScript code for getting and setting value from CRM/CE Lookupfield.

// Get the Lookup Value.
function getLookupDetails(executionContext) {
    var formContext = executionContext.getFormContext();
    var entityName, entityId, entityLabel, lookupFieldObject;
    lookupFieldObject = formContext.data.entity.attributes.get(“parentcontactid”);
    if (lookupFieldObject.getValue() != null) {
        entityId = lookupFieldObject.getValue()[0].id.slice(1, -1);
        entityName = lookupFieldObject.getValue()[0].entityType;
        entityLabel = lookupFieldObject.getValue()[0].name;
    }
}
// Set the Lookup Value.
function setLookupField(executionContext) {
    var formContext = executionContext.getFormContext();
    var lookupData = new Array();
    var lookupItem = new Object();
    lookupItem.id = “74a968c5-6505-ea11-a81e-000d3a300ec6”;
    lookupItem.name = “Nancy”;
    lookupItem.entityType = “contact”;
    lookupData[0] = lookupItem;
    formContext.data.entity.attributes.get(“parentcontactid”).setValue(lookupData);

}


Hope this helps.


Happy 365’ing

Gopinath

One thought on “Get/Set Lookup field value using JavaScript in Dynamics CRM/Dynamics 365 CE

  1. Anjali Vinu February 22, 2020 / 5:40 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s