Sonoma Partners Microsoft CRM and Salesforce Blog

Lookups - Null vs Empty Array

The other day I discovered an interesting ‘gotcha’ when working with a lookup in JavaScript.  A business requirement called for some JavaScript to be registered when a lookup value changed and then execute certain logic based on if the lookup had a value or not. 

This is pretty straightforward logic and could be handled easily with the following code:

var customerValue = Xrm.Page.getAttribute('parentcustomerid').getValue();
if (!customerValue) {
   // do some logic
}
else
{
   // do some other logic
}

Come to find out, this works for the most part but there is one scenario where it falls short which is where the ‘gotcha’ comes in. 

  1. Record form loads and the lookup doesn’t have a value
  2. The lookup has a value and the user selects the lookup and hits the “Delete” key
  3. The lookup has a value and the user clicks the magnifying glass, then “Look Up More Records” and then clicks “Remove Value” on the subsequent dialog
In the first two scenarios with the above JavaScript code, the customerValue variable will be null and will work as expected.  In the third scenario, the customerValue variable will be an empty array and not work as expected as it isn’t null.


Therefore we need to update the block of code with the following:

var customerValue = Xrm.Page.getAttribute('parentcustomerid').getValue();
if (!customerValue || customerValue.length == 0) {
   // do some logic
}
else
{
   // do some other logic
}

Now the code is flexible and will handle all 3 scenarios where the lookup value doesn’t exist.

Note:  This was tested in CRM 2015 Update 1 and CRM 2016

Topics: Microsoft Dynamics CRM Microsoft Dynamics CRM 2015 Microsoft Dynamics CRM 2016 Microsoft Dynamics CRM Online