Friday, June 14, 2013

Sneak Peek: Salesforce Polymorphic keys

Polymorphic key is a relationship field which can relate to more than one type of object as parent. Unlike Lookup and Master-detail relationships which are related to a single object, Polymorphic keys can refer to multiple objects.

As of date, Polymorphic keys cannot be created by developers. They are available for specific objects out of the box for e.g. WHOID and WHATID in Task and Event objects.

Sneak Peak: Salesforce Polymorphic Keys
As we know, Salesforce’s data model is strictly relationship based, and the type of objects at both the ends of the relationship is fixed. So, if an object is to be related with multiple objects, then a separate relationship field has to be created for each relationship. Polymorphic keys are required to maintain relationship with multiple types, for e.g. task/ event might be related with various type of records viz. Account, Contact etc. So, a polymorphic key helps in establishing unique access to such disparate relationships.

Polymorphic keys are hard to handle!! As they are polymorphic the queries/ data manipulation can be tricky, as the related object can be anything, and hence the operations might or might not succeed. For e.g. functionality to update a field on Account may not work with Contact.

In order to implement such functionality, the type of the object is to be determined and hence the operations are to be applied. Further, the objects would need to be retrieved separately.

With Summer ’13 release, Polymorphic keys have become more friendly. They can be used in SOQL queries to filter out specific types, based on type specific filter criteria. Following are few ways of handling polymorphic keys in SOQL:-

List = [SELECT TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN Amount END FROM Event];
This would conditionally return value of field "Phone" if event is related to Account and value of field "Amount" if event is related to Opportunity

Note: TYPEOF is currently available as a Developer Preview as part of the SOQL Polymorphism feature.

Filter results by Type
List = [SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')];
This would return only those events which are related with an Account or Opportunity.

For more details refer


Popular Posts