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
mat_tone_84mat_tone_84 

trigger for mass update campaignmember doesn't update all record but only one

 


trigger update_date on CampaignMember (after update) {
   //create list of members
   list<CampaignMember> memb = new List<CampaignMember>();
   for (CampaignMember m : Trigger.new) {
       memb.add(m);
   }
   list<CampaignMember> memb_old = new List<CampaignMember>();
   for (CampaignMember m2 : Trigger.old) {
       memb_old.add(m2);
   } 
if (memb.get(0).status == 'sent' && memb_old.get(0).status == 'not sent' ){   

list<contact> list2 = [select id,date_last_sent_email__c from contact where Id = :memb.get(0).contactid];
        for(contact c: list2){
            if (memb.get(0).type_campagna__c.contains('%email%')){
               list.get(0).date_last_sent_email__c  = system.today();  
            }
        }
        update list2 ;
}
}

 hi!

this code works properly with one member, if I update more than 20 records the trigger update only one member and not all 20!!

Maybe Do have I to optimize the code, any suggestions ?

thanks

 

Best Answer chosen by Admin (Salesforce Developers) 
ShrutiShruti

This is because "memb.get(0)" will return the first record only. So you are modifying the first record multiple times. This can be avoided by using a for loop and "memb.get(i)" where "i"  is loop variable.

All Answers

ShrutiShruti

This is because "memb.get(0)" will return the first record only. So you are modifying the first record multiple times. This can be avoided by using a for loop and "memb.get(i)" where "i"  is loop variable.

This was selected as the best answer
mat_tone_84mat_tone_84

thanks.

I will try your suggestions...

 

If I use a loop I have to check the size of member's list, is correct?

 

If I don't do this, I don't know how many loops do... 

 

 

mat_tone_84mat_tone_84

if I insert a loop I have too many soql queries

mat_tone_84mat_tone_84

I solve the problem with loop.

I create a list of contact before the loop and after I use loop to check every contact for my work,thanks!