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


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:


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?


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');

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

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

Leave a Comment