Tuesday, September 20, 2016

CRM Alternate keys with OptionSet fields

The alternative keys feature introduced in CRM 2015 U1 turns out to be extremely useful, especially for integration scenrios in which you might want to keep a record of an “external key” from another system or you want to enforce duplicate prevention (for real).

In some cases you would like to make the alternative key contain an OptionSet type of field. For example, I wanted to define an alternative key based on “Contact Type” and “Email” so that CRM could check that no contacts of the same type with the same email address.
However, when you try to define the key on the contact entity I could no select my “Contact Type” field as part of the key:




So I can see a number of fields and realize that only fields of numeric or text value are available to pick. After some research I found that it is documented in the SDK that only these fields can be added to a key:



















So no luck! The only option you have is to create a hidden text field which will hold the value of your OptionSet but as text and then add that field to your key. I try to define this field as a calculated fiueld but then again, calculated fields cannot be added to alternate keys (this is by experiment, not by documentation). Therefore, I had to define a business rule to populate that field based on the options of your OptionSet. In my example, my OptionSet has options “Nurse” and “Doctor” so I create the business rule as follows (note you should set “Scope” to “Entity”)



Now I am able to add the calculated field to my key:





After this is done, I can test to make sure I can create both a nurse and a doctor with the same email but if I try to create 2 nurses with the same email I get the error:



So this works. It is not the most elegant solution since you are essentially duplicating data. However, if you must include an OptionSet field as part of a key this could be an easy way to enforce it :-)

Enjoy!!




No comments:

Post a Comment