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
AbhishekJAbhishekJ 

Need help with a trigger, not updating the value when a corresponding record is deleted.

Trigger 'CommunicationContentTrigger' is written on a custom object 'Communication_Content__C' to populate value from First Name field on Contact object to Salutation field on Communication Content object. But the value on Salution is not getting updated when a contact is deleted. I am new to apex. Would anyone be able to help me with modifying the trigger.

Here is the Trigger:
trigger CommunicationContentTrigger on Communications_Content__c (
  before insert, 
  before update) {
    CommunicationContentTriggerHandler handler = new CommunicationContentTriggerHandler(true,200,false);
    if (Trigger.isBefore) {
        //call your handler.before method
      if(Trigger.isInsert) {
        handler.OnBeforeInsert(Trigger.new);
      } else if(Trigger.isUpdate) { 
        handler.OnBeforeUpdate(Trigger.oldMap,Trigger.new);
      }
      
    } 
}

Here is apex class handler
public with sharing class CommunicationContentTriggerHandler {

  private boolean m_isExecuting = false;
  private boolean force_update = false;
  private integer BatchSize = 0;

  public CommunicationContentTriggerHandler(boolean isExecuting, integer size, boolean forceUpdate){
    m_isExecuting = isExecuting;
    BatchSize = size;
    force_update = forceUpdate ;
  }

  public void OnBeforeInsert(Communications_Content__c[] newRecords){

    updateSalutationField(null,newRecords);
   
  }


  public void OnBeforeUpdate(Map<Id,Communications_Content__c> oldRecords, Communications_Content__c[] updatedRecords){
    
  }

  public void updateSalutationField(Map<Id,Communications_Content__c> oldRecords, Communications_Content__c[] newRecords) {
     
      Set<Id> companyID = new Set<Id>(); 
      Set<String> correspPref = new Set<String>(); 
      
      List<Communications_Content__c> ccToUpdate = new List<Communications_Content__c>();
      for(Communications_Content__c cc :newRecords) {
          System.debug('---- Company: ' + cc.Company__c + ' Correspondence_Preference__c: ' + cc.Correspondence_Preference__c); 
          if(oldRecords == null && cc.Company__c != null && cc.Correspondence_Preference__c != null) {
             
              companyID.add(cc.Company__c); 
              correspPref.add(cc.Correspondence_Preference__c); 
          }
          
          if(oldRecords != null && (cc.Company__c != oldRecords.get(cc.Id).Company__c
             || cc.Correspondence_Preference__c  != oldRecords.get(cc.Id).Correspondence_Preference__c )) {

                          if(cc.Company__c == null || cc.Correspondence_Preference__c == null) {
                                 cc.Salutation__c  = '' ;
                                 
                                 cc.Correspondence_Preference__c='';
                                 ccToUpdate.add(cc);              
                          }
                           else {
                               System.debug('Not null');
                       
                                companyID.add(cc.Company__c);
                        correspPref.add(cc.Correspondence_Preference__c);
                       }
          }

         
          if(oldRecords != null && cc.Company__c != null && cc.Correspondence_Preference__c != null 
            && (cc.Company__c == oldRecords.get(cc.Id).Company__c
             || cc.Correspondence_Preference__c  == oldRecords.get(cc.Id).Correspondence_Preference__c )){ 
                     System.debug('Blank update');
                 
                     companyID.add(cc.Company__c); 
                   correspPref.add(cc.Correspondence_Preference__c); 
          }
        
      }
    System.debug('MKlich Companies: '+ CompanyID); 
    System.debug('MKlich Coresponding Pref: : '+ correspPref); 

     
      if(companyID.size() > 0 && correspPref.size() > 0) {
      Map<string,List<String>> accCPandContactMap = new Map<string,List<String>>();
    
       for(Correspondence_Preference__c cp : [Select Id,Contact__c,Contact__r.FirstName,Contact__r.Email,RecordType.Name,Company__c,Seniority_Rank_On_Contact__c, Contact__r.International_Salutation_Type__c, Contact__r.LastName from Correspondence_Preference__c where Company__c IN :companyID AND RecordType.Name IN :correspPref AND Recipient_Type__c = 'To' AND Contact__r.Email != null AND ( NOT Contact__r.Email LIKE '%@generalatlantic.com' ) order by Seniority_Rank_On_Contact__c, Contact__r.FirstName]){
      
      
        string key = cp.Company__c+cp.RecordType.Name.toLowerCase();
        System.debug('Key is: '+key);
        if(!accCPandContactMap.containsKey(key)) {
          accCPandContactMap.put(key,new List<String>{});
          System.debug('Inside the if accCPandContactMap: '+accCPandContactMap.keySet());
          System.debug('Inside the if accCPandContactMap: '+accCPandContactMap.Values());
        }
       
        String name = '';
        if(cp.Contact__r.International_Salutation_Type__c != null){
          if(cp.Contact__r.International_Salutation_Type__c == 'Japanese'){
            name = cp.Contact__r.LastName + '-san';
          }
          else if(cp.Contact__r.International_Salutation_Type__c == 'Thai' && cp.Contact__r.FirstName != null){
            name = 'Khun ' + cp.Contact__r.FirstName;
          }
        }
        else if(cp.Contact__r.FirstName != null){
          name = cp.Contact__r.FirstName;
        }
        if(name != ''){
          accCPandContactMap.get(key).add(name);
            
        }

        
      }
      for(Communications_Content__c cc :newRecords) {
        if(cc.Company__c != null && cc.Correspondence_Preference__c != null) {
          string key = cc.Company__c+cc.Correspondence_Preference__c.toLowerCase();
          string valToUpdate = '' ;
          if(accCPandContactMap.containsKey(key)) {
            List<String> contacts = accCPandContactMap.get(key);
            valToUpdate = replaceLast(String.join(contacts,', '),', ',' and ');
            
            valToUpdate += ',';
          }
          cc.Salutation__c = valToUpdate ;
          
          if(String.isEmpty(cc.Salutation__c)) {
            cc.Correspondence_Preference__c = '';
          }
          
          ccToUpdate.add(cc);
        }
      }
    }
    
    if(force_update && ccToUpdate.size() > 0 ){
        update ccToUpdate;
    }

  }

  private string replaceLast(string mainStr, string substrToReplace, string replacedBy) {
    integer index = mainStr.lastIndexOf(substrToReplace);
    if (index == -1)
      return mainStr;

    return mainStr.substring(0, index) + replacedBy + mainStr.substring(index+substrToReplace.length());
  }
}

​​​​​​​
Lokesh KumarLokesh Kumar
You need to use the Contact trigger after delete event to get this task done.
AbhishekJAbhishekJ
Thanks a lot for the advice. Would you be able to help me a bit further and take a look at the contact trigger and handler class and let me know how do I modify the trigger to get this done.
​​​​​​​This issue is not limited to delete, I need the field to update when a new contact record is added as well.
One more thing to note here is that there is another cusotm object involed Correspondence Preference with master detail relationship, contact being the master. So until a corresponding record on Correspondence Preference object is created, I do not expect anything to change on communication content object. Would be glad to walk you through the whole functionality if that helps.
Here is the trigger:
trigger ContactTrigger on Contact (after insert, after update,after delete,after undelete) { 
    
    if(Trigger.isAfter) {
            if(Trigger.isUpdate) {
            ContactTriggerHandler.onAfterUpdate(Trigger.new,Trigger.oldMap);
            }
            
            if(Trigger.isInsert){
             ContactTriggerHandler.OnAfterInsert(Trigger.new);
            }
            
            if(Trigger.IsDelete){
                ContactTriggerHandler.OnAfterDelete(Trigger.old);
            }
            
            if(Trigger.IsUnDelete){
                ContactTriggerHandler.OnUndelete(Trigger.new);
            }
    }
     
}

Here is the handler apex class:
public class ContactTriggerHandler {
    
    public static void onAfterUpdate(List<Contact> newContacts, Map<id,Contact> oldContacts) {
            updateSortedCorrespondencePreferneceData(newContacts,oldContacts);
            updateSalutationOnCommunicationContent(newContacts,oldContacts);             
            id cpCapitalPartnerRT = fetchRecordTypeId('Account','CP Capital Partner');
            List<Contact> newList = new List<Contact>();
            
            set<Id> oldAndNewAccountIds = new set<id>();
            for(Contact con : newContacts) {
                oldAndNewAccountIds.add(con.accountId);
                oldAndNewAccountIds.add(oldContacts.get(con.id).accountId);
            }
            
            Map<Id,Account> accountDetails = new Map<Id,Account>([Select Id,RecordTypeId from Account where Id in :oldAndNewAccountIds]);
            for(Contact con : newContacts) {
                    if(accountDetails !=NULL && con!= Null && con.accountId != oldContacts.get(con.Id).accountId  ) { 
                        if(  accountDetails.containsKey(con.accountId) && (accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT || accountDetails.get(oldContacts.get(con.Id).accountId).recordTypeId == cpCapitalPartnerRT) ) {
                            newList.add(con);
                        }

                    } else if(accountDetails !=NULL && con!= Null && accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT ) { 
                        newList.add(con);
                    }
            }        
           
            Email_InformationClass.getEmailTableData(newList,oldContacts); 
            updateCPIntralinksAccess(newContacts,oldContacts);  
    }
    
    public static void OnAfterDelete(contact[] oldList){
        
        updateCPIntralinksAccess(oldList, null);
    }
    
     public static void OnAfterInsert(contact[] newList){
        
        updateCPIntralinksAccess(newList, null);
    }
     
    public static void OnUndelete(contact[] newList){ 
         
         updateCPIntralinksAccess(newList,null);
    }
	private static void updateSalutationOnCommunicationContent(List<Contact> newContacts, Map<id,Contact> oldContacts){
        set<id> contactsToProcess = new set<id>();
        for(Contact con : newContacts) {
            if((String.isNotBlank(con.email) && !con.email.contains('@generalatlantic.com'))  && ((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
                                                                                                  (con.FirstName != oldContacts.get(con.id).FirstName)) || (con.International_Salutation_Type__c!= oldContacts.get(con.Id).International_Salutation_Type__c || String.isBlank(oldContacts.get(con.Id).email))
              )
            {
                
                        contactsToProcess.add(con.id);
            }
        }
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Company__c, RecordType.Name from Correspondence_Preference__c where Recipient_Type__c = 'To' AND Contact__c In :contactsToProcess]);
            set<string> cpNames = new Set<String>();
            set<string> accountNames = new Set<String>();
            for(Correspondence_Preference__c cp : corrPrefToProcess) {
                cpNames.add(cp.RecordType.Name);
                accountNames.add(cp.Company__c);
            }
            List<Communications_Content__c> ccList = new List<Communications_Content__c>([Select Id,Salutation__c,Company__c,Correspondence_Preference__c from Communications_Content__c where Company__c IN :accountNames AND Correspondence_Preference__c IN :cpNames]);
            CommunicationContentTriggerHandler handler = new CommunicationContentTriggerHandler(true,200,true);
            handler.updateSalutationField(null,ccList); 
        }
    } 
    private static void updateSortedCorrespondencePreferneceData(List<Contact> newContacts, Map<id,Contact> oldContacts) {
        set<id> contactsToProcess = new set<id>();
        for(Contact con : newContacts) {
            if((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
               (con.Email != oldContacts.get(con.id).Email)
              ) {
                  contactsToProcess.add(con.id);
              }
        }
        
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Commitment__c, RecordTypeId from Correspondence_Preference__c where Contact__c In :contactsToProcess]);
            
            CorrespondenceTriggerHandler.getCommRecTypeData(corrPrefToProcess,null,false);
        }
    }
    private static id fetchRecordTypeId(string sObj, string rt) {
        System.debug('fetch params>>'+sObj + '<<<rt>>>'+rt);
        String recordtypeId = Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId(); 
        return Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId();
        
    }
    public static void updateCPIntralinksAccess(List<Contact> newContacts, Map<id,Contact> OldMap){
        
        Map<ID,List<contact>> mapConWithAcc = new Map<ID,List<contact>>();
        List<account> accList = new List<account>();
        String temp= '';
        Map<Id,String> accUpdateMap = new Map<Id,String>();
        Set<ID> accid = new Set<ID>();
        
        for(contact con: newContacts){
            
            if(oldMap == null || oldMap.get(con.id).CP_Intralinks_Access__c != con.CP_Intralinks_Access__c ){ 
                accid.add(con.accountid); 
                
            }
        }
        
        for(Account acc : [Select id,CP_Intralinks_Access__c,(Select id,CP_Intralinks_Access__c,accountid from contacts) from account where id in :accid]) {
            
            set<string> val = new set<string>();
            
            String finalVal = '' ;
            
            for(Contact ct : acc.contacts) {
                
                if(String.isNOtBlank(ct.CP_Intralinks_Access__c)) {
                    
                    val.addAll(ct.CP_Intralinks_Access__c.split(';')); 
                    
                }
                
                
                
            }
            
            List<String> valList = new List<String>();
            
            valList.addAll(val);
            
            if(valList.size() > 0) {
                
                finalVal = String.join(valList,',');
                
            }
            
            acc.CP_Intralinks_Access__c = finalVal ;
            
            accList.add(acc);
            
        }
        
        
        if(accList.size() > 0) {
            update accList ;
        }
        
        
    }
}


 
AbhishekJAbhishekJ
If you could just help me with taking care of the delete scenario for now and figure out adding the new contact later myself. Business is really behind me for delete scenario right now.
Lokesh KumarLokesh Kumar
remove all other methods from the class and trigger and try testing. Let me know what is the error you are getting.
AbhishekJAbhishekJ
Probably this is how the trigger would look like.
trigger ContactTrigger on Contact (after insert, after update,after delete,after undelete) {
    if(Trigger.isAfter) {
            if(Trigger.IsDelete){
                ContactTriggerHandler.OnAfterDelete(Trigger.old);
            }
    }
}
Could you please help me update the class
Sorry I am very new to this.
Lokesh KumarLokesh Kumar
What is the relationship between Contact and Communication object?
AbhishekJAbhishekJ
There is no direct relationship between Communication Content and Contact object. 
Communication Content has look up relationship with Company.
Company has master-detail relationship with Contact object.