+ Start a Discussion
GMASJGMASJ 

Opportunity and Campaign

Hi, 

  There is very old trigger logic written in our instance this is failing due to not being bulkified can someone please suggest how to bulkifie below trigger 
trigger updateprimarycampaign on Opportunity (Before Update ,After insert)
{
 if ( checkRecursive_updateprimarycampaign.runOnce()) 
 {
    if(Trigger.isUpdate)
    {
        try
        {
            for (Opportunity op : Trigger.new) 
            {
                CampaignMember cm = [SELECT CampaignId FROM CampaignMember 
                                     where ContactId = :op.Contact__c and HasResponded = true and 
                                           CreatedDate <= :op.createddate limit 1];
               if ( cm.CampaignId == NULL)
               {
                    op.CampaignId = null;
               } 
               else
               {
                op.CampaignId = cm.CampaignId;
                }
            }
        }
        catch (Exception e)
        {
            for (Opportunity op : Trigger.new) {
                op.CampaignId = null;
            }
        }
    }
    else if (Trigger.isInsert)
    {
        Set<ID> setoppId = new Set<Id>();
        String getCampaignId;

        for(Opportunity opp: Trigger.new ) 
        {
            setoppId.add(opp.id);
        }
     
        List<Opportunity> lstOpp = [select id , CampaignId from Opportunity where id in :setoppId ];
        
        try
        {
            List<Opportunity> lstOppToUpdate = new List<Opportunity>();
            for (Opportunity op : lstOpp) 
            {
                CampaignMember cm = [SELECT CampaignId FROM CampaignMember 
                                     where ContactId = :op.Contact__c and HasResponded = true and
                                           CreatedDate <= :op.createddate limit 1];
               
               if ( cm.CampaignId == NULL)
               {
                    op.CampaignId = null;
                    lstOppToUpdate.add(op);
               } 
                else
               {
                   op.CampaignId = cm.CampaignId;
                   lstOppToUpdate.add(op);
                }
            }
            if(lstOppToUpdate.size() > 0 )
            {
                update lstOppToUpdate;
            }
        }
        catch (Exception e)
        {
            /*
                for ( Opportunity op : lstOpp ) 
                {
                    op.CampaignId = null;
                }
                update lstOpp;
            */
             update lstOpp; 
        }
    }   
}
}
Thanks
Sam
 
Best Answer chosen by GMASJ
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Sam

Try the below code:
trigger updateprimarycampaign on Opportunity (Before Update ,After insert)
{
 if ( checkRecursive_updateprimarycampaign.runOnce()) 
 {
    if(Trigger.isUpdate)
    {
	Set<Id> ConIds=new Set<Id>();
	 for (Opportunity op : Trigger.new) 
            {
			ConIds.add(op.contact__c);
			}
	 List<CampaignMember> cmList = new List<CampaignMember>([SELECT CampaignId FROM CampaignMember 
                                     where ContactId in: ConIds and HasResponded = true and 
                                           CreatedDate <= :op.createddate]);
       Map<Id,Id> camCon=new Map<Id,Id>();
	   for(CampaignMember cm:cmList)
	   {
	   camCon.put(cm.ContactId,cm.CampaignId);
	   }
	   for(Opportunity op : Trigger.new)
	   {
	     if(camCon.containsKey(op.Contact__c))
		 {
		 op.CampaignId=camCon.get(op.Contact__c);
		 }
		 else
		 op.CampaignId=null;
	   }
	}
	else if (Trigger.isInsert)
    {
	 List<Opportunity> lstOppToUpdate = new List<Opportunity>();
	  for(Opportunity opp: Trigger.new ) 
        {
            setoppId.add(opp.id);
        }
     
        List<Opportunity> lstOpp = [select id , CampaignId from Opportunity where id in :setoppId ];
		Set<Id> ConIds=new Set<Id>();
	 for (Opportunity op : lstOpp) 
            {
			ConIds.add(op.contact__c);
			}
	 List<CampaignMember> cmList = new List<CampaignMember>([SELECT CampaignId FROM CampaignMember 
                                     where ContactId in: ConIds and HasResponded = true and 
                                           CreatedDate <= :op.createddate]);
       Map<Id,Id> camCon=new Map<Id,Id>();
	   for(CampaignMember cm:cmList)
	   {
	   camCon.put(cm.ContactId,cm.CampaignId);
	   }
	   for(Opportunity op : lstOpp)
	   {
	     if(camCon.containsKey(op.Contact__c))
		 {
		 op.CampaignId=camCon.get(op.Contact__c);
		 lstOppToUpdate.add(op);
		 }
		 else
		 {
		 op.CampaignId=null;
		 lstOppToUpdate.add(op);
	   }
	   
	   }
	    if(lstOppToUpdate.size() > 0 )
            {
                update lstOppToUpdate;
            }
		
	}
 }
}

Hope this will be helpful.
Thanks.

All Answers

Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Sam

Try the below code:
trigger updateprimarycampaign on Opportunity (Before Update ,After insert)
{
 if ( checkRecursive_updateprimarycampaign.runOnce()) 
 {
    if(Trigger.isUpdate)
    {
	Set<Id> ConIds=new Set<Id>();
	 for (Opportunity op : Trigger.new) 
            {
			ConIds.add(op.contact__c);
			}
	 List<CampaignMember> cmList = new List<CampaignMember>([SELECT CampaignId FROM CampaignMember 
                                     where ContactId in: ConIds and HasResponded = true and 
                                           CreatedDate <= :op.createddate]);
       Map<Id,Id> camCon=new Map<Id,Id>();
	   for(CampaignMember cm:cmList)
	   {
	   camCon.put(cm.ContactId,cm.CampaignId);
	   }
	   for(Opportunity op : Trigger.new)
	   {
	     if(camCon.containsKey(op.Contact__c))
		 {
		 op.CampaignId=camCon.get(op.Contact__c);
		 }
		 else
		 op.CampaignId=null;
	   }
	}
	else if (Trigger.isInsert)
    {
	 List<Opportunity> lstOppToUpdate = new List<Opportunity>();
	  for(Opportunity opp: Trigger.new ) 
        {
            setoppId.add(opp.id);
        }
     
        List<Opportunity> lstOpp = [select id , CampaignId from Opportunity where id in :setoppId ];
		Set<Id> ConIds=new Set<Id>();
	 for (Opportunity op : lstOpp) 
            {
			ConIds.add(op.contact__c);
			}
	 List<CampaignMember> cmList = new List<CampaignMember>([SELECT CampaignId FROM CampaignMember 
                                     where ContactId in: ConIds and HasResponded = true and 
                                           CreatedDate <= :op.createddate]);
       Map<Id,Id> camCon=new Map<Id,Id>();
	   for(CampaignMember cm:cmList)
	   {
	   camCon.put(cm.ContactId,cm.CampaignId);
	   }
	   for(Opportunity op : lstOpp)
	   {
	     if(camCon.containsKey(op.Contact__c))
		 {
		 op.CampaignId=camCon.get(op.Contact__c);
		 lstOppToUpdate.add(op);
		 }
		 else
		 {
		 op.CampaignId=null;
		 lstOppToUpdate.add(op);
	   }
	   
	   }
	    if(lstOppToUpdate.size() > 0 )
            {
                update lstOppToUpdate;
            }
		
	}
 }
}

Hope this will be helpful.
Thanks.
This was selected as the best answer
GMASJGMASJ
Thanks Bharagavi  your code helped me to fix the issue I modified little bit to make it work below is the working code. 
 
I need your help in building test class to get 75+ code coverage 
 
Trigger updateprimarycampaign on Opportunity (Before Update ,After insert)
{
    Set<Id> ConIds=new Set<Id>();
    Set<datetime> OpCreateddate = new set<datetime>();
    Set<id> setoppId=new set<id>();
 if ( checkRecursive_updateprimarycampaign.runOnce()) 
 {
    if(Trigger.isUpdate)
    {
   
     for (Opportunity op : Trigger.new) 
            {
            ConIds.add(op.contact__c);
            OpCreateddate.add(op.createddate);
            }
     List<CampaignMember> cmList = new List<CampaignMember>([SELECT id,CampaignId,ContactId FROM CampaignMember 
                                     where ContactId in: ConIds and HasResponded = true and 
                                           CreatedDate <= :OpCreateddate]);
       Map<Id,Id> camCon=new Map<Id,Id>();
       for(CampaignMember cm:cmList)
       {
       camCon.put(cm.ContactId,cm.CampaignId);
       }
       for(Opportunity op : Trigger.new)
       {
         if(camCon.containsKey(op.Contact__c))
         {
         op.CampaignId=camCon.get(op.Contact__c);
         }
         else
         op.CampaignId=null;
       }
    }
    else if (Trigger.isInsert)
    {
     List<Opportunity> lstOppToUpdate = new List<Opportunity>();
      for(Opportunity opp: Trigger.new ) 
        {
            setoppId.add(opp.id);
            OpCreateddate.add(opp.createddate);
        }
     
        List<Opportunity> lstOpp = [select id , CampaignId,Contact__c from Opportunity where id in :setoppId ];
        Set<Id> ConIds=new Set<Id>();
     for (Opportunity op : lstOpp) 
            {
            ConIds.add(op.contact__c);
            }
     List<CampaignMember> cmList = new List<CampaignMember>([SELECT id,CampaignId,ContactId FROM CampaignMember 
                                     where ContactId in: ConIds and HasResponded = true and 
                                           CreatedDate<=:OpCreateddate]);
       Map<Id,Id> camCon=new Map<Id,Id>();
       for(CampaignMember cm:cmList)
       {
       camCon.put(cm.ContactId,cm.CampaignId);
       }
       for(Opportunity op : lstOpp)
       {
         if(camCon.containsKey(op.Contact__c))
         {
         op.CampaignId=camCon.get(op.Contact__c);
         lstOppToUpdate.add(op);
         }
         else
         {
         op.CampaignId=null;
         lstOppToUpdate.add(op);
       }
       
       }
        if(lstOppToUpdate.size() > 0 )
            {
                update lstOppToUpdate;
            }
        
    }
 }
}

 Below is the old test class which is giving 62% code coverage. need your suggestion to improve the coverage. 
@isTest(SeeAllData = true)
public class test_updateprimarycampaign{
    static testMethod void TestCampaignMember (){

        Test.startTest();
        
        Account testAcc = new Account (Name = 'Test Account 2342343', Email_Domain__c = 'sudhir1231@samarth.com');
       {
        insert testAcc;
        }

        //Creates Contact to be linked to Campaign Member
        Contact testContact = new Contact(FirstName = 'TestContactF245634', LastName = 'TestContactL', Email = 'none@navinet.net',accountid=testAcc.Id,LeadSource = 'Community' );
        insert testContact;
        
        Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
        
        Opportunity testOpp = new Opportunity (Name = 'Test Name 987191',                       
                                     AccountId = testAcc.Id,
                                     Type = 'New Customer',                                   
                                     StageName = 'Open',
                                     Amount = 50000.00,
                                     CloseDate = System.today(),
                                     LeadSource = 'Community'
                                     );
    {
    insert testOpp;
   }

        //Creates a new campaign memeber, associaites it with 1 provider sales campaign, and inserts
        CampaignMember newMember = 
        new CampaignMember(ContactId = testContact.id, status='Sent', campaignid = cp.id);
        insert newMember;

       Opportunity opp1a = [SELECT Id,campaignid 
                            FROM Opportunity
                            WHERE Id = :testOpp.Id];

        opp1a.campaignid = cp.id;
        
        update opp1a;

        Test.stopTest();

    }
}


Thanks
Sudhir
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Sudhir,
Try the below code:
 
@isTest(SeeAllData = true)
public class test_updateprimarycampaign{
    static testMethod void TestCampaignMember (){

        Test.startTest();
        
        Account testAcc = new Account (Name = 'Test Account 2342343', Email_Domain__c = 'sudhir1231@samarth.com');
       
        insert testAcc;
        

        //Creates Contact to be linked to Campaign Member
        Contact testContact = new Contact(FirstName = 'TestContactF245634', LastName = 'TestContactL', Email = 'none@navinet.net',accountid=testAcc.Id,LeadSource = 'Community' );
        insert testContact;
        
        Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
        //Creates a new campaign memeber, associaites it with 1 provider sales campaign, and inserts
        CampaignMember newMember = 
        new CampaignMember(ContactId = testContact.id, status='Responded', campaignid = cp.id);
        insert newMember;
		
        Opportunity testOpp = new Opportunity (Name = 'Test Name 987191',                       
                                     AccountId = testAcc.Id,
                                     Type = 'New Customer',                                   
                                     StageName = 'Open',
                                     Amount = 50000.00,
                                     Contact__c=testContact.id,
                                     CloseDate = System.today(),
                                     LeadSource = 'Community'
                                     );
    
    insert testOpp;
   

        

       Opportunity opp1a = [SELECT Id,campaignid 
                            FROM Opportunity
                            WHERE Id = :testOpp.Id];

        opp1a.campaignid = cp.id;
        
        update opp1a;

        Test.stopTest();

    }
	 static testMethod void TestCampaignMember1 (){

        Test.startTest();
        
        Account testAcc = new Account (Name = 'Test Account 2342343', Email_Domain__c = 'sudhir1231@samarth.com');
       
        insert testAcc;
        

        //Creates Contact to be linked to Campaign Member
        Contact testContact = new Contact(FirstName = 'TestContactF245634', LastName = 'TestContactL', Email = 'none@navinet.net',accountid=testAcc.Id,LeadSource = 'Community' );
        insert testContact;
        
       
        Opportunity testOpp = new Opportunity (Name = 'Test Name 987191',                       
                                     AccountId = testAcc.Id,
                                     Type = 'New Customer',                                   
                                     StageName = 'Open',
                                     Contact__c=testContact.id,
                                     Amount = 50000.00,
                                     CloseDate = System.today(),
                                     LeadSource = 'Community'
                                     );
    
    insert testOpp;
   

        

       Opportunity opp1a = [SELECT Id,campaignid 
                            FROM Opportunity
                            WHERE Id = :testOpp.Id];

        opp1a.campaignid = cp.id;
        
        update opp1a;

        Test.stopTest();

    }
}

Hope it will be useful.
Thanks.