I have junction object (Junction__c) with two master-detail relationships to 'contacts' and 'Training_Session__c'. I'm trying to write a query to generate a list of email addresses for use in a visual force page. Here's what the APEX class looks like.

   List<SObject> contact_list = [SELECT id, contact__r.email, contact__r.name FROM Junction__c WHERE Training_Seesion__c = :ApexPages.currentPage().getParameters().get('id')];

Mapping the values of a result (getPopulatedfiedldsAsMap()) returns:

Contact_list field name is Id, value is a0C3D0000007x2jUAA
Contact_list field name is Contact__c, value is 0033D00000NopQPQAZ
Contact_list field name is CurrencyIsoCode, value is USD
Contact_list field name is Contact__r, value is Contact: {Email=ronnidadamo@cuvox.de, Name=Ronni Adamo, Id=0033D00000NopQPQAZ, CurrencyIsoCode=USD}

I'm struggling with the proper syntax to access contact_list.contact__r [(contact or contact__c)].email. Whenever attempting to access the value in a loop, the code fails to compile with

Error: Compile Error: Variable does not exist: contact__r
  • 1
    Can you post your for loop? Why are you querying into a generic SObject? – EricSSH Apr 30 '18 at 18:53
  • If you used the type Junction__c you would have access to the field contact__r, but since its a generic type, you need to use getSObject – battery.cord Apr 30 '18 at 18:58

When using a generic SObject, you need to use getSObject:

for(SObject record: contact_list) {
  Contact conRecord = record.getSObject('Contact__r');
  • Thanks Fox! addresses = (string) contact_IDs.getsobject('contact__r').get('email'); did the trick. – Nathan Bradbury Apr 30 '18 at 20:48

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.