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

5 comments:

  1. Thanks for this great post, i find it very interesting and very well thought out and put together. I look forward to reading your work in the future.
    defer parsing of js wordpress

    ReplyDelete
  2. super tight code. love it.

    say, is the parentcontactid the name of the lookup value? I have a lookup field on a form but I am not sure what the name is....where do you find parentcontactid?

    ReplyDelete
  3. I dugg some of you post as I cerebrated they were very beneficial very useful see here

    ReplyDelete