I have a requirement to update CampaignMember field by comparing a custom object which is not link to Campaign Member table. But the fields are same in both the objects.
My scenario is when the campaign, contact and status is added or updated in custom object, the latest entry with the status should be updated in CampaignMember table against by comparing CampaignId, ContactID and Status of Campaign Member.
The below is my code.
Trigger updateCampaignStatus on Responses__c (before update,after insert, after delete) {
if(trigger.isinsert && trigger.isbefore && trigger.isupdate){
map<id,Responses__c> mapcam = trigger.newmap;
list<CampaignMember> resp = new list<CampaignMember>();
list<CampaignMember> cam = [select id, CampaignId, Contactid, Status from CampaignMember where CampaignId in : mapcam.keyset()];
for(CampaignMember c : cam){
c.Status = mapcam.get(c.Id).Response_Status__c;
resp.add(c);
insert resp;
}
update resp;
}
if(trigger.isafter && trigger.isdelete){
map<id,Responses__c> delres = trigger.oldmap;
list<CampaignMember> ccc = [select id, CampaignId,Contactid, Status from CampaignMember where CampaignId in : delres.keyset()];
delete ccc;
}
}
But it is not updating the status of CampaignMember by comparing the CampaignID, Contact ID.
c.Status = mapcam.get(c.CampaignId).Response_Status__c;
2) Second, do NOT EVER, perform DML operations inside a loop. You will hit DML limits, pretty easily. 3) I don't understand, why do you perform an insert, than an update of all the CampaignMember records?