Get / Set Lookup field value using javascript in CRM

Get / Set Lookup field value using javascript in CRM :

Get Lookup Field Value :

function getLookupDetails() {
    try {
        var lookupentityName, lookuprecordId, lookuprecordname, lookupFieldObject;
        lookupFieldObject = Xrm.Page.getattribute(“gb_lookupfieldschemaname”);
        if (lookupFieldObject != null && lookupFieldObject.getValue() != null) {
            lookuprecordId = lookupFieldObject.getValue()[0].id;
            lookupentityName = lookupFieldObject.getValue()[0].entityType;
            lookuprecordname = lookupFieldObject.getValue()[0].name;
        }
    }
    catch (ex) {
        alert(” Exception in getLookupDetails : ” + ex);
    }
}

Set Value to Lookup Field :

function setLookupField() {
    try {
        //Create ArrayObject and setValue
        var lookupData = new Array(); var lookupItem = new Object();
        lookupItem.id = myTeamId; // Lookuprecord Guid
        lookupItem.name = myTeamName; // Lookuprecord Name
        lookupItem.entityType = “team”; // Lookupentity Schema Name
        lookupData[0] = lookupItem;
        Xrm.Page.getAttribute(“gb_lookupfieldschemaname”).setValue(lookupData);
        // or
        Xrm.Page.getAttribute(“gb_lookupfieldschemaname”).setValue([{
            id: myTeamId,
            name: myTeamName,
            entityType: “team”
        }]);
    }
    catch (ex) {
        alert(” Exception in setLookupField : ” + ex);
    }
}

That’s it. Enjoy 🙂

Advertisements