Retrieving Data from Lookup Fields

Nathan Eccles, 28 May 2010

If you’ve ever tried using JavaScript with lookup values in CRM I’m sure you will have found that they are quite a lot different from the other types of attributes. With only a small amount of JavaScript code you can retrieve the following values from any lookup value.

Below is the code I used to get those 4 values:

Here’s an explanation of the code:

// Defines the Lookup field Value.
var lookupItem = crmForm.all.mag_productid.DataValue;

// Check to make sure the Lookup field contains data (if there is no data and you attempt to populate the value fields you will get an error message).
if (lookupItem != null) {
// Populate the field “Text Value” with the text value of the lookup field. (The name of the record you have selected)
    crmForm.all.mag_textvalue.DataValue = lookupItem[0].name;
// Populate the field “Entity Type” with the schema name of the lookup field. (The type of record displayed e.g. “product”)
    crmForm.all.mag_entitytype.DataValue = lookupItem[0].typename;
// Populate the field “GUID” with the GUID value of the lookup field. (The unique ID given to the record you have selected)
    crmForm.all.mag_guid.DataValue = lookupItem[0].id;
// Populate the field “Entity Type Code” with the entity type code of the lookup field. (The unique number value given to the entity)
    crmForm.all.mag_entitytypecode.DataValue = lookupItem[0].type;
}

To use this code:

  1. Open the entity which contains the lookup field you wish to pull these data values from.
  2. Create 4 new nvarchar attributes to capture the 4 values shown above.
  3. Place the 4 attributes on your form and put the following code in the onLoad form event, and onChange event of the lookup field ensure the Event is enabled box is checked;

    var lookupItem = crmForm.all.lookupfield.DataValue;

    if (lookupItem != null) {
        crmForm.all.textvalue.DataValue = lookupItem[0].name;
        crmForm.all.entitytype.DataValue = lookupItem[0].typename;
        crmForm.all.guid.DataValue = lookupItem[0].id;
        crmForm.all.entitytypecode.DataValue = lookupItem[0].type;
    }

  4. Replace lookupfield with the attribute name of the lookup field you are using.
  5. Replace textvalue with the attribute name of the field you wish to populate with the attribute name.
  6. Repeat this for entitytype, guid, and entitytypecode.
  7. Preview your changes to ensure that they are working correctly and then publish your entity.

Now it’s unlikely that this code would be used as is, but hopefully with a little imagination and creativity you will be able to utilise it to make your CRM system more dynamic and smooth flowing.
If you are looking for more JavaScript code please look through the other Magnetism blog posts, or post here and we’ll see if we can help you out.