Search code examples
salesforceapexapex-codesoqlsalesforce-lightning

Get Contact Emails of Currently Active Account as List


Given: A Salesforce user is viewing an account page.

Desired Output: All Emails of Contacts related to the Account currently viewed as a List object.

My code:

SELECT Email FROM Contact WHERE Id IN (SELECT ContactId FROM AccountContactRelation WHERE AccountId = ApexPages.CurrentPage.getParameters().get('id'))

This does not retrieve any results. When using a fixed number instead of ApexPages.CurrentPage.getParameters().get('id'), the Emails are correctly returned.

I'm sort of new to Apex. Could anyone point out what I am doing wrong?


Solution

  • To achieve the desired output you need to use SOQL variable injection.

    You can do this by creating a variable first and then referencing the variable inside the SOQL using : and the variable name:

    String theAccountId = ApexPages.CurrentPage.getParameters().get('id');
    List<Contact> theContacts = [SELECT Email FROM Contact WHERE Id IN (SELECT ContactId FROM AccountContactRelation WHERE AccountId = :theAccountId)];