+ Start a Discussion
Cesar Restrepo 4Cesar Restrepo 4 

We currently use Leads and Contacts in Campaigns, here is my questions... Is there any way to prevent contacts from being deleted if they are members of an active campaign?

Gaurav Jain 7Gaurav Jain 7

Use trigger to prevent contacts from being deleted if they are members of an active campaign

Mark it as Best Answer, if it helps​​
 
trigger campaigncheck on Contact (before delete) {
    
   Set<id> contactIds = new Set<id>();
    for (contact a : Trigger.old)
        contactIds.add(a.id); 
    
    Map<Id, List<campaignmember>> campainmembermap = new Map<Id, List<campaignmember>>();
    for (campaignmember camobj : [select id,Name,CampaignId,ContactId from campaignmember where ContactId  in :contactIds and Campaign.IsActive = True]) {
        List<campaignmember> l = campainmembermap.get(camobj.ContactId);
        if (l == null) {
            l = new List<campaignmember>();
            campainmembermap.put(camobj.ContactId, l);
        }
        l.add(camobj);
    }
    
   for (contact a : Trigger.old)
   {
       List<campaignmember> cammemberlist = campainmembermap.get(a.Id);
       if(cammemberlist.size() > 0)
       {
           a.addError('This is campaign memeber, you can not delete');
       }
   }
}