You need to sign in to do that
Don't have an account?
How to retrieve relationship fields from generic sobject or aggregate result objects
This is just some example code, I don't want the focus of what I'm doing to cloud the concept I'm trying to figure out.
code:
sobject[] something = [SELECT Contact.FirstName, Contact.Account.Name, contact.account.type from Contact];
I've used sobject[] here instead of contact[] because in my project the query is dynamic and could be from a different table.
My question is, how do I get the relationship field from this? Normally, I know you can do this:
string theName = something[0].Account.Name;
However, this results in the error: Field expression not allowed for generic SObject
How do I get around this?
With custom relationships you'd use soemthing similar to:
s.getSObject('Your_Custom_Object__r').('Some_Field__c');
All Answers
With custom relationships you'd use soemthing similar to:
s.getSObject('Your_Custom_Object__r').('Some_Field__c');
Also, for the record, I figured out I can do this in visualforce :
{!something['Account']['Name']}
Just in case anyone else comes across this
i.e. Object1__r.Objectt2__r.Object3__r.Some_Field__c
It doesn't work for... s.getSObject('Object1__r.Objectt2__r.Object3__r').('Some_Field__c'); ???
String objRelStr = 'Objectt2__r.Object3__r.Some_Field__c';
List<String> objRelList = objRelStr.split('.');
sObject s= Object1__r;
for(Integer i=0; i< (objRelList.size() - 1); i++ ) {
s = s.getSObject(objRelList[i]);
}
Sytem.debug(s.get('Some_Field__c'));
just for someone who is looking for something reusable
public static Object getFieldValueFromSobject(Sobject sob,String fullyQualifiedfieldName){
List<String> relationFieldsMappings = fullyQualifiedfieldName.split('\\.');
System.debug('relationFieldsMappings '+relationFieldsMappings);
String fieldName = relationFieldsMappings[relationFieldsMappings.size()-1];
SObject finalSob = sob.clone(true,true,true,true) ;
for(Integer count= 0; count<relationFieldsMappings.size()-1;count++){
System.debug('finalSob'+finalSob);
System.debug('sob'+sob);
finalSob = finalSob.getSObject(relationFieldsMappings[count]);
}
return finalSob.get(fieldName);
}