Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 13 down vote accepted

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.

share|improve this answer
1  
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 at 0:24
    
@BritishBoyinDC yep, that's why I pointed to all "get" methods! :) –  eyescream Jan 22 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 at 0:40

sObject acc = sObject.get('Account'); value = acc.get('MyAccountField__c');

share|improve this answer
2  
There's no way this will compile, you'll be slapped with Invalid field Account for [source object's name]. –  eyescream Jan 22 at 0:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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