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
Semira@gmail.comSemira@gmail.com 

Campaign influence to Opportunity via apex

Hi, 

So I know Campaign Influence API isn't available to apex and visualforce page. So my turn around work was fetch the contact id from opportunity, Then run a query of all the campaign memeber where it matches the id, fetch the ID of the campaign. Then add to the Primary Campign on the opportunity. 

However, I'm not really expert at Maps so here's where I'm a little stuck. Looking at the code, how do I fetch the ID of the campaign and added to the Opportunity list? 

 
Set<ID> ContactIds = new Set<ID>();
        for (Opportunity rec: workingOpps)
        {
            if(rec.Contact__c != null)
            {
                ContactIds.add(rec.Contact__c);
            }
        }
        
        Map<ID, CampaignMember> CampaignMember = new Map<id, CampaignMember>(
            [select 
            id, CampaignId from CampaignMember where ContactId in: ContactIds]);
        
        for (Opportunity opp : workingOpps)
        {
            //Check if the map is empty
            Boolean empty = CampaignMember.isEmpty();
            if(empty)
            {
                continue;
            }
            //check if the campaign id exit in the job. 
            
            //CampaignMember memberID = CampaignMember.get(????????????);
            
            
            //opp.Campaign = CampaignMember.Campaign.id;
        }

Any help or ideas are appreciated. Thanks 
ManojjenaManojjena
Hi Semira ,

Try with below code !!
Set<ID> ContactIds = new Set<ID>();
        Map<id, CampaignMember> CampaignMember = new Map<id, CampaignMember>();
        for (Opportunity rec: workingOpps)
        {
            if(rec.Contact__c != null)
            {
                ContactIds.add(rec.Contact__c);
            }
        }
        for(CampaignMember camp:[select 
            id, CampaignId,ContactId from CampaignMember where ContactId in: ContactIds]){
		  CampaignMemberMap.put(camp.ContactId,camp);
		}
         for (Opportunity opp : workingOpps)
        {
		  if(!CampaignMemberMap.isEmpty() && CampaignMemberMap.get(opp.Contact__c) != null){
		     opp.Campaign = CampaignMemberMap.get(opp.Contact__c).CampaignId;
		  }
		}
Let me know if it helps!!
Thanks
Manoj