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?

  • eyescream

    eyescream Correct answer

    8 years ago

    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.

    As an added bonus, you can also use getsObjects() to go the other way down the tree: e.g. List so = [Select Id, (Select Id from Contacts) from Account LIMIT 10]; List cons = so[0].getSObjects('Contacts');

    @BritishBoyinDC yep, that's why I pointed to all "get" methods! :)

    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...!

    In case it helps someone else (I was wondering this): Using the '__r' will work. So if your dynamic code has something like List sList = [Select Name, Custom__r.Name from Contact]; it can be addressed with sList[0].getSobject('Custom__r').get('Name');

    The link was dead - edited.

    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.

    @AdrianLarson how do we check for fields that does not have value for example , in my case `(String)obj.getSObject('Account').get('Name')` sometime does not have value and apex is throwing an error in that case to counter this I have applied `obj.getSObject('Account') !=null ` check but seems not working at all

    You should consider asking that as its own question @Hunt

    @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()`.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM