Friday, 6 December 2019

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

1 comment: