You need to sign in to do that
Don't have an account?
Jean Grey 10
Trigger add contact to campaign
I'm working on a trigger to add contacts to a campaign based on temporary fields stored on the contact. This is working for new campaign members inserted, but I need to update the status on the campaign member record if it changes on the contact. I understand I need to update the existing campaign member rather than try to insert a new one, but I'm unsure how to go about that. Here is my code:
Any help is much appreciated!
trigger addToCampaignContact on Contact (after insert, after update) { public List<CampaignMember> cmList = new List<CampaignMember>(); public Set<Id> conSet = new Set<Id>(); public List<Contact> conList = new List<Contact>(); //create list of contact members to add for(Contact c:Trigger.New){ if(c.Campaign_Id__c != NULL && c.Member_Status__c != NULL){ conSet.add(c.Id); cmList.add( new CampaignMember( CampaignId = c.Campaign_Id__c, ContactId = c.Id, Status = c.Member_Status__c, UTM_Name__c = c.UTM_Campaign_Name__c, Content__c= c.UTM_Content__c, Medium__c=c.UTM_Medium__c, Source__c=c.UTM_Source__c, UTM_Term__c=c.UTM_Term__c )); }} system.debug('insert cmList '+cmList); if(!cmList.isEmpty()){ insert cmList;} } /* //update contacts back to null to prep for future campaign conList = [SELECT Id, Campaign_Id__c, Member_Status__c, UTM_Campaign_Name__c FROM Contact WHERE Id IN :conSet]; for(Contact c:conList){ c.Campaign_Id__c=NULL; c.Member_Status__c=NULL; c.UTM_Source__c=NULL; c.UTM_Medium__c=NULL; c.UTM_Campaign_Name__c=NULL; c.UTM_Content__c=NULL; c.UTM_Term__c=NULL; } system.debug('update conList '+conList); //update conList; */Error when I try to update the member status field on the contact to update the campaign member:
Error:Apex trigger addToCampaignContact caused an unexpected exception, contact your administrator: addToCampaignContact: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, Already a campaign member.: []: Trigger.addToCampaignContact: line 32, column 1
Any help is much appreciated!
All Answers