Working with lookup fields in CRM when using JavaScript is a little different due to the way the entity is handled. The following snippets will allow you to both read a value in a look-up, as well as to populate a value in the look-up (for cases when you need to pre-define a value).

Reading the selected value in a lookup:

var lookupItem = new Array();
lookupItem = Xrm.Page.getAttribute("new_specialty").getValue();

if(lookupItem[0] != null)
{
    var name = lookupItem[0].name;
    var guid = lookupItem[0].id;
    var entType = lookupItem[0].entityType;
}

Writing to a lookup:

if(new_Country == null)
{
    // alert("Preparing to set Country:");
    var countryName = "Canada";
   
    var lookupData = new Array();
    var lookupItem = new Object();
    lookupItem.id="{A53E3645-912A-E111-92BB-00155D146C19}";
    lookupItem.name=countryName;
    lookupItem.entityType="new_country";
   
    lookupData[0] = lookupItem;
    // alert("Assigning Country to Field:");
    Xrm.Page.getAttribute("new_relatedcountryid").setValue(lookupData);
}

Enjoy!

Advertisements