Get / Set Lookup field value using javascript in CRM

 

Hello everyone,

In this tutorial we will cover how to Get Set Lookup field value using javascript in CRM.

 

What is lookup field?

A Lookup field type represents the relationship attribute on the related entity.

 

Required Attributes of lookup fields

id : The GUID of the item. Required for set.

name : The name of the item to be displayed. Required for set.

entityType : The entity name of the item. Required for set.

 

How to get values of a lookup field?
function getLookupDetails() {
    var entityName, entityId, entityLabel, lookupFieldObject;

    // parentaccountid is the lookup field name that we try to reach its values
    lookupFieldObject = Xrm.Page.data.entity.attributes.get('parentaccountid');
    if (lookupFieldObject.getValue() != null) {
        entityId = lookupFieldObject.getValue()[0].id;
        entityName = lookupFieldObject.getValue()[0].entityType;
      	entityLabel = lookupFieldObject.getValue()[0].name;
    }

	// Here you can use the id, name and entityType of the lookup
  	// Here also you can get the entity and the attribute values of it
  	// To do that please refer to the Note below !
}

 Note: You can refer to my article (Retrieve Data using OData queries with Javascript in CRM 2013) to pass the id of a lookup field and get values of an entity. 

 

How to set a lookup field value?

The function below sets new_teamid lookup field:


function setLookupField() {

    var lookupData = new Array();
    var lookupItem = new Object();
    //Set the GUID
    lookupItem.id = myTeamId;
    //Set the name
    lookupItem.name = myTeamName;
    lookupItem.entityType = "team";
    lookupData[0] = lookupItem;

    //If existing value is empty, then set new value
    var existingValue = Xrm.Page.getAttribute("new_teamid").getValue();

    if (existingValue === null) {
        Xrm.Page.getAttribute("new_teamid").setValue([{
            id: myTeamId,
            name: myTeamName,
            entityType: "team"
        }]);
    } else {
        return;
    }
}

I hope you enjoyed this tutorial 🙂

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *