0

Is it possible to get SObjectType dynamically from field token like Account.Name?

2 Answers 2

2

Update Spring '23

There is now a method on the DescribeFieldResult called getSObjectType().

This can be used to get the sObjectType from the sObjectField token.

e.g.

Schema.SObjectField myField = Account.Name;
Schema.SObjectType theFieldsObject = myField.getDescribe().getSObjectType();
3

No, it is not*. The only method that a field token has is getDescribe(), and the DescribeFieldResult class doesn't contain any methods that return which SObject the field is for.

*: Not for all fields, at least. It is likely possible if you are working with a relationship field and use the relationship name. I don't think that approach is practical/useful though. Since you need to hardcode the field token or use an sobject token/describe to get at the field tokens/describes, you should have a better source for that information anyway.

4
  • DescribeFieldResult.getReferenceTo() but for field token seems to return always an empty list Account.Name.getDescribe().getReferenceTo()? Feb 25, 2021 at 13:33
  • @gpoluch getReferenceTo() only returns data for relationship fields, and it gives you the parent sobject, not the sobject your field is actually on.
    – Derek F
    Feb 25, 2021 at 13:47
  • Indeed. Thanks for explanation @Derek F. Feb 25, 2021 at 13:51
  • there is a brute force approach -- I sure wish SFDC would implement the OP's rquest
    – cropredy
    Feb 25, 2021 at 23:00

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .