Get all objects available on polymorphic field

Polymorphic Fields In Salesforce
Polymorphic Fields In Salesforce

In salesforce there is concept called polymorphic fields. Its a lookup relationship type field with more than more one object. Unlike Lookup and Master-detail relationships which are related to a single object, Polymorphic keys can refer to multiple objects. This article is based on polymorphic fields where we will discuss following topics.

Scenario :

  • How to get all lookup objects present of Polymorphic field.
  • Find all objects present on Related To (WhatId) field of Task Object 
  • Find all objects present on WhoId field of Task Object 
  • working on polymorphic lookup field in salesforce

Objects present on Task->WhatId

polymorphic fields in salesforce

Get all Objects from Task->WhatId 

				
					Map < String, Schema.SObjectType > describeResult = Schema.getGlobalDescribe();
Map < String, String > mapOfObjects = new Map < String, String > ();
Schema.DescribeFieldResult describeField;
for (Schema.SObjectField strFld: describeResult.get('Task').getDescribe().fields.getMap().Values()) {
  describeField = strFld.getDescribe();
  if (describeField.getType() == Schema.DisplayType.REFERENCE && describeField.getName() == 'WhatId') {
    for (Schema.SObjectType reference: describeField.getReferenceTo())
      mapOfObjects.put(reference.getDescribe().getName(), reference.getDescribe().getLabel());
  }
}

System.debug('mapOfObjects ' + mapOfObjects);
				
			

Objects present on Task->Who

polymorphic objects in salesforce

Get all Objects from Task->WhoId

				
					Map < String, Schema.SObjectType > describeResult = Schema.getGlobalDescribe();
Map < String, String > mapOfObjects = new Map < String, String > ();
Schema.DescribeFieldResult describeField;
for (Schema.SObjectField strFld: describeResult.get('Task').getDescribe().fields.getMap().Values()) {
  describeField = strFld.getDescribe();
  if (describeField.getType() == Schema.DisplayType.REFERENCE && describeField.getName() == 'WhoId') {
    for (Schema.SObjectType reference: describeField.getReferenceTo())
      mapOfObjects.put(reference.getDescribe().getName(), reference.getDescribe().getLabel());
  }
}

System.debug('mapOfObjects ' + mapOfObjects);
				
			

Leave a Reply