function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Will EdwardsWill Edwards 

How do I create a class that includes all contacts related to accounts related to a campaign?

I want to create a VF page that shows fields from all contact records that belong to accounts related to a particular campaign. To do that I'll need to create a class in Apex that pulls all contacts with any of the account IDs that belong to campaign members. I understand it will involved nested statements, but I'm not quite sure how to get started. Thanks.
Nagendra ChinchinadaNagendra Chinchinada
Hi Will,

Crete your controller like this. FinalConList contains all contacts related to accounts related to the Campaign . You can include all fields of contact in query(FinalConList  query) and extend columns in VF.
public class CampaignController {
    public Campaign camp {get; set;}   
    public List<Contact> FinalConList {get; set;} // Which holds all contacts related to accounts related to a campaign
    
    
    public CampaignController(ApexPages.StandardController controller) {
        camp = (Campaign) controller.getRecord();        
       // List<contact> conlst = [select AccountId from contact where Id IN (Select contactId from campaignmember where campaignId =:camp.Id )];  
        
        set<Id> AccountId = New set<Id>();
        
        for(contact Cont :  [select AccountId from contact where Id IN (Select contactId from campaignmember where campaignId =:camp.Id )]){
            AccountId.add(Cont.AccountId);
        }
        
        FinalConList = New List<Contact>();
        FinalConList = [SELECT Id,Name FROM Contact WHERE AccountId IN :AccountId ];
        
    }
    
}

VF page,
 
<apex:page standardController="Campaign" extensions="CampaignController">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!FinalConList}"  var="con">
            <apex:column headerValue="Name"  value="{!con.Name}"/>
            <apex:column headerValue="Account Name" value="{!con.Account.Name}"/>
        </apex:pageBlockTable> 
    </apex:pageBlock>
</apex:page>

Let me know if it helps.
Will EdwardsWill Edwards
Nagendra, this is very helpful. Could you help me understand one thing?  What if I only want to include contacts in FinalConList where the contact meets certain criteria? (e.g. Status__c="Stage A")
Nagendra ChinchinadaNagendra Chinchinada
 If u want this criteria at campaign member level, then add filter in line no 13 as shown below.
for(contact Cont :  [select AccountId from contact where Id IN (Select contactId from campaignmember where Status__c = 'Stage A' AND campaignId =:camp.Id )]){


If u want on final contact list then change the line no 17 as shown below,
 
FinalConList = [SELECT Id,Name FROM Contact WHERE Status__c = 'Stage A' AND AccountId IN :AccountId ];