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.

  • 8
    As an added bonus, you can also use getsObjects() to go the other way down the tree: e.g. List<sObject> so = [Select Id, (Select Id from Contacts) from Account LIMIT 10]; List<Contact> cons = so[0].getSObjects('Contacts'); – BritishBoyinDC Jan 22 '14 at 0:24
  • @BritishBoyinDC yep, that's why I pointed to all "get" methods! :) – eyescream Jan 22 '14 at 0:26
  • Just took me a while to realize that the phrase 'Returns the values for the specified field.' meant I could also get back the whole list...think the docs could use some additional detail...! – BritishBoyinDC Jan 22 '14 at 0:40
  • 5
    In case it helps someone else (I was wondering this): Using the '__r' will work. So if your dynamic code has something like List<sObject> sList = [Select Name, Custom__r.Name from Contact]; it can be addressed with sList[0].getSobject('Custom__r').get('Name'); – HungryBeagle May 5 '15 at 13:35
  • 1
    Probably would be worth adding checks for a null parent if you were going to genericize this functionality. I guess in this case though neither parent is nillable. – Adrian Larson Oct 10 '17 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.