Pages

Friday, March 13, 2009

Microsoft CRM: Look Up Site Address button

One of the simpler hacks I've ever accomplished in CRM, is the ability to provide a button on an Entity form that allows you to populate address fields on that same Entity with the addresses from Sites. Most of this functionality comes from the Look Up Customer Address code by Michael Höhne over at Stunnware--which, if you haven't guessed by now, is like my CRM idol.

Here's the code:

var url = '/' + ORG_UNIQUE_NAME + '/_controls/lookup/lookupsingle.aspx?class=Site&objecttypes=4009&browse=0&bindingcolumns=address1_line1%2caddress1_line2%2caddress1_line3%2caddress1_city%2caddress1_stateorprovince%2caddress1_postalcode%2caddress1_country&ShowNewButton=0&ShowPropButton=1';

var selectedAddress = window.showModalDialog(url, null, 'dialogWidth:400px;dialogHeight:400px;resizable:yes'); 

if (selectedAddress != null) { 
  var addressFields = selectedAddress.items[0].values; 
  
  for (var index in addressFields) { 
    if (addressFields[index] && addressFields[index].name) { 
      var control = document.getElementById('<Prefix Value>' + addressFields[index].name.replace(/address1_/,'')); 
      
      if (control) { 
        control.DataValue = addressFields[index].value; 
      } 
    } 
  } 
}

This code works best when all of the address fields on your form use a prefix on the name of the fields originating in the Site entity. For example, the target custom_addressline1 field from a custom entity matches the field address1_line1 on the Site entity, making "custom_address" the value for <Prefix Value>. Otherwise, you'll end up mapping each of the fields in the script.

I take the liberty of stripping the "address1_" portion of each source field name from the Site. As you can see, there's an interesting feature of lookupsingle.aspx: the variable bindingcolumns can be used to set a series of invisible fields to return in the values array. I take the above code, and drop it into the ISV.config XML file under a button element for the entity's menu, and voila! The button now generates a nice, little lookup window populated with all my Sites. Selecting one automatically populates address fields on my form. It's possible that you could extend this functionality to System User records as well, and many other record types. I just haven't done so myself.