function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mtbclimbermtbclimber 

Determing SObject type in Polymorphic objects (i.e. ProcessInstance)

I received an email with the following inquiry:

 

Is there an easy way to determine the underlying SObject type when using objects that store polymorphic keys e.g. ProcessInstance? I tried the following :
 
for(ProcessInstance inst: [Select TargetObject.Id, Status, Id From ProcessInstance]){
                SObject sObj = inst.TargetObject;
                System.debug('>>>>>>>>>>>>>>>>>>>>>'+(sObj.getSObjectType()));
}
 
And I get this:
18.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;VALIDATION,INFO;WORKFLOW,INFO
8:6:22.566|EXECUTION_STARTED
8:6:22.566|CODE_UNIT_STARTED|[EXTERNAL]System Log Window
8:6:22.569|SOQL_EXECUTE_BEGIN|[1,27]|Aggregations:0|Select TargetObject.Id, Status, Id From ProcessInstance
8:6:22.574|SOQL_EXECUTE_END|[1,27]|Rows:4|Duration:5
8:6:22.574|METHOD_ENTRY|[3,1]|System.debug(String)
8:6:22.574|METHOD_ENTRY|[3,39]|SObject.getSObjectType()
8:6:22.574|METHOD_EXIT|[3,39]|getSObjectType()
8:6:22.574|USER_DEBUG|[3,1]|DEBUG|>>>>>>>>>>>>>>>>>>>>>Name
8:6:22.574|METHOD_EXIT|[3,1]|debug(ANY)
 
Do I have to use the "Id" prefix to determine what Object the record is associated with?

 

 

And the answer to this is that yes using the ID prefix is one way to do this but an easier one is to recognize that polymorphic relationships like  ProcessInstance.TargetObject and Event/Task.who/what point to the Name object. The name object has a convenient "Type" field which provides the sobject type information. So simply adding that field to the above query should provide the information required in this inquiry:

 

 

 

for(ProcessInstance inst: [Select TargetObject.Id, TargetObject.type, Status, Id From ProcessInstance]){
SObject sObj = inst.TargetObject;
System.debug('>>>>>>>>>>>>>>>>>>>>>'+(sObj.getSObjectType()));

System.debug('The Type for id: ' + sObj.id + ' is: ' + sObj.type);
}

 

Message Edited by mtbclimber on 03-08-2010 08:29 AM
Best Answer chosen by Admin (Salesforce Developers) 
tmatthiesentmatthiesen

Schema.DescribeFieldResult has a boolean method:isNamePointing() which allows you to programmatically determine if a field is a polymorphic relationship.  If you have a dynamic query and need to determine the sobject type at runtime, then I would recommend leveraging the above method to determine your code path for resolving the sobject type.

 

doc link