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
Michael FinkMichael Fink 

given a campaignID and contactID how can you check if a contact is a campaign member for the given campaign in apex

say I have 

Contact c= findContact();
ID campID= getCampID();

how can I...

A)
find if c is a campaign member of the campaign related to campID

B)
if it is not a member make it a member?

Thanks for any help I've just started learning salesforce and have been getting pretty frustrated with SOQL 
Best Answer chosen by Michael Fink
Ankit Gupta@ DeveloperAnkit Gupta@ Developer
Hi Michael,

Try below code as reference:



list<CampaignMember> lstCampaignMember=[select id from CampaignMember where ContactId='contactid' and CampaignId ='CampaignId'];
if(lstCampaignMember.size()<=0)
{
    CampaignMember newCM = new CampaignMember(
CampaignId = campaignId,
ContactId = c.Id,
status = 'Sent' );

insert newCM;
}