Using sObject.get() to fetch a field value from a related parent object

I have a contact in a generic sObject in apex and while I’m able to easily get detail field values using

sObject.get('MyContactField__c')

I’m not able to get fields off the related parent object, and I’m sure the related field is in memory, based on the debug logs. This returns a runtime error:

sObject.get('Account.MyAccountField__c')

with the error

Invalid field Account.MyAccountField__c’ for Contact

How do I get a field value off of a parent on a generic sObject?

Answer

You need getSobject() to traverse relationship “up” in a dynamic way.

sObject acc = [SELECT Owner.Profile.Name FROM Account LIMIT 1];
String profileName = (String) acc.getSobject('Owner').getSobject('Profile').get('Name');
System.debug(profileName);

Check all dynamic get* methods in the Sobject instance methods docs.

Attribution
Source : Link , Question Author : greenstork , Answer Author : Caspar Harmer

Leave a Comment