59

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?

1 Answer 1

99

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.

10
  • 11
    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'); Jan 22, 2014 at 0:24
  • 10
    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'); May 5, 2015 at 13:35
  • 2
    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, 2017 at 12:49
  • 1
    @Hunt null check works for me, definitely post new question? sObject o = [SELECT Manager.Name FROM User LIMIT 1]; sObject manager = o.getSobject('Manager'); String name = manager != null ? (String) manager.get('Name') : 'Nope'; System.debug(name);. You could also SELECT ManagerId and check that... for related lists - I think list will always be there (never null value) but it's perfectly OK for it to be isEmpty().
    – eyescream
    Jan 23, 2020 at 6:26
  • 2
    For null checks, using the save navigation operator should do the trick: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… Jul 22, 2021 at 21:38

You must log in to answer this question.

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