Working with CRM Form Lookup Controls Programmatically

Lately, I have been asked a number of times about how to programmatically work with Lookup controls on CRM forms. Basically, you can read values from and set new values to almost all of the CRM form controls, including Lookups. You can write Jscript code that runs on CRM OnLoad/OnSave/OnChange form Events and manipulate the values of form controls programmatically. Among lots of useful benefits of our form (a.k.a. client side) programming model, JScripts are particularly useful for data validation and setting default values (other examples are accessing rich functionality hosted on a web service as shown in one of my earlier blogs).

BTW: We do have some of this info already documented in the SDK docs and we will update the next refresh with all of these samples. I thought I give you a headstart given the number of questions and emails I received.

Here are some samples, one for read and one for write:

//Reading values from a Lookup control named primarycontatctid on the Account form


var lookupItem = new Array;

// This will get the lookup for the attribute primarycontactid on the Account form.

lookupItem = crmForm.all.primarycontactid.DataValue;

// If there is data in the field, show it in a series of alerts.

if (lookupItem && lookupItem[0] != null)


    // The text value of the lookup.


    // The entity type name.


    // The GUID of the lookup.


    // The entity type code of the lookup: 1=account, 2= contact.



//Setting values to pricelevelid lookup control on the Opportunity form.

//In this example, the price level is set to Retail.


//Create a lookupItem to store the values that you want to set to a target Lookup control

var lookupItem = new Array();

// Values on the signature of LookupControlItem are: GUID of pricelevel, type code of pricelevel and finally the name of the lookup value

lookupItem[0] = new LookupControlItem ("{F31BB38A-0EC0-403F-99A6-3AF469D7D76E}", 1022, "Retail");

//Set the form control value to the lookupItem just created

crmForm.all.pricelevelid.DataValue = lookupItem ;


BTW this code also works for CustomerId fields on the form (a common question:-))


Happy coding:-)