Thursday, July 22, 2010

Javascript: Succinct Set Lookup value

The CRM 4 SDK for setting a lookup is very verbose and this post shares a simpler way to set a lookup value.

The following code example from the SDK shows how to set values in a field of type Lookup.
//Create an array to set as the DataValue for the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem= new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = '{1AAC1363-01A1-DB11-8432-0003FF9CE217}';
lookupItem.typename = 'account';
lookupItem.name = 'A Bike Store';
// Add the object to the array.
lookupData[0] = lookupItem;
// Set the value of the lookup field to the value of the array.
crmForm.all.parentaccountid.DataValue = lookupData;

Things to note above are that we create an array instance and the an object instance. The Javascript language provides a short hand way of creating instances of these classes.

The Object shorthand allows us to replace the lookupItem variable (defined in lines 4 to 8 above) with the following:
{id:'{1AAC1363-01A1-DB11-8432-0003FF9CE217}', 
 typename:'account',
 name:'A Bike Store'}

We can create an array instance by using square brackets [] so lookupData (defined in lines 2 and 10) could become:
[lookupItem]

Putting all together we can remove both the variables in the example and use the following instead:
crmForm.all.parentaccountid.DataValue = [{ 
 id:'{1AAC1363-01A1-DB11-8432-0003FF9CE217}', 
 typename:'account', 
 name:'A Bike Store'}];
In conclusion the shorthand makes a lot cleaner code once you understand the JavaScript shorthand notation