+ Start a Discussion
OutsiderOutsider 

Any way to make a trigger work for bulk update and online update?

Hi Friends,

 

Anyone can tell me how to make a trigger work for bulk update and online update?  I code below to update contact from Campaign Member.  It only works if less than 10 records are added to Campaign Member, no matter is from Add to Campaign function or dataloader.

 

trigger UpdateContact1stSamplingDataafterinsertCampaignMember on CampaignMember (after insert) {   
     Map<Id, List<CampaignMember>> CampaignMembersByContactId = new Map<Id, List<CampaignMember>>();
     for (CampaignMember campmem : trigger.new) {
         if(campmem.Contact_Type__c == 'First Contact'){
               List<CampaignMember> temp = new List<CampaignMember>();            
                temp.add(campmem);            
                CampaignMembersByContactId.put(campmem.ContactId, temp); 
         }//end if
     }//end for
     Map<Id, Contact>  ContactsById = new Map<Id, Contact>([SELECT Id FROM Contact WHERE Id in :CampaignMembersByContactId.keySet()]);
     for(Id ContactId : CampaignMembersByContactId.keyset()) {  
         if(CampaignMembersByContactId.get(contactId).get(0).stage__c == '1' ) {
             ContactsById.get(contactId).Stage_1_Date__c = CampaignMembersByContactId.get(contactId).get(0).Created_Date__c;
              ContactsById.get(contactId).stage_1_Status__c = CampaignMembersByContactId.get(contactId).get(0).Status;
           }//end if

     }//end for
     update(ContactsById.values());

jhenningjhenning

try this code snippet. If I understand your code properly, I think this will work better.

 

 

trigger UpdateContact1stSamplingDataafterinsertCampaignMember on CampaignMember (after insert) {   
     Map<Id, CampaignMember> CampaignMembersByContactId = new Map<Id, CampaignMember>();
     for (CampaignMember campmem : trigger.new) {
         if(campmem.Contact_Type__c == 'First Contact'){
                CampaignMembersByContactId.put(campmem.ContactId, campmem); 
         }//end if
     }//end for
     for(List<Contact> contacts: [SELECT Id FROM Contact WHERE Id in :CampaignMembersByContactId.keySet()]) {
     	for(Contact c:contacts){
	        if(CampaignMembersByContactId.get(c.Id).stage__c == '1' ) {
	        	c.Stage_1_Date__c = CampaignMembersByContactId.get(c.Id).Created_Date__c;
	            c.stage_1_Status__c = CampaignMembersByContactId.get(c.Id).Status;
	        }//end if
     	}
     	update contacts;
     }//end for
}