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
Neeraj Sharma 103Neeraj Sharma 103 

Hi Everyone Anyone Help Me I want to use After Insert,After Update,After Delete in one trigger

Hi Everyone Anyone Help Me I want to use After Insert,After Update,After Delete in one trigger  througth  trigger Handler and 
i want to call all these events in one method from trigger in trigger handler class  

Anyone Have Example anyone do this types of scenarios when used these events so please help me
Best Answer chosen by Neeraj Sharma 103
Deepali KulshresthaDeepali Kulshrestha
Hi Neeraj Sharma,

Greetings to you!

I have used After Insert, After Update, and Before Delete in one trigger and also I used a single method in all three cases. I have used it before delete because after deleting a record we cannot use its id that's why I used before delete. And, it's also a best practice to not use after delete always tries to use before delete.
 
Trigger
---------------------------------
trigger UpadteAccountName on Contact (after insert,after update,before delete){
    if(Trigger.isafter){
        if(Trigger.isinsert || Trigger.isupdate){
            
            ContactTriggerHandler.updateAccountName(Trigger.new,Trigger.OperationType);
        }
    }
    if(Trigger.isbefore){
        if(Trigger.isdelete){
            ContactTriggerHandler.updateAccountName(Trigger.old,Trigger.OperationType);
        }
    }
    
}


Handler class
----------------------------------------------

public class ContactTriggerHandler {
    public static void updateAccountName(List<Contact> contactList,TriggerOperation operationObject){
        try{
            String operationObj = string.valueOf(operationObject);
            
            String updatedAccName = '';
            List<String> stringList = New List<String>();
            
            List<Account> accList = new List<Account>();
            
            List<Id> contactIdSet = new List<Id>();
            
            if(contactList.size()>0){
                for(Contact contactObj : contactList){
                    if(contactObj.AccountId != Null){
                        contactIdSet.add(contactObj.id);
                    }
                }
                List<Contact> conList = New List<Contact>();
                conList = [SELECT Name,AccountId,Account.Name FROM Contact WHERE Id In :contactIdSet LIMIT 50000];
                for(Contact conatctObj : conList){
                    if(operationObj == 'AFTER_INSERT' || operationObj == 'AFTER_UPDATE'){
                        conatctObj.Account.Name = conatctObj.Account.Name + ' ' +conatctObj.Name;
                        accList.add(conatctObj.Account); 
                    }
                    else if(operationObj == 'BEFORE_DELETE'){
                        
                        stringList = conatctObj.Account.Name.split(' ');
                        stringList.remove(stringList.indexof(conatctObj.Name));
                        for(String strObj : stringList){
                            updatedAccName = updatedAccName + ' ' +strObj; 
                        }
                        conatctObj.Account.Name = updatedAccName;
                        accList.add(conatctObj.Account);
                        
                    }
                    
                } 
                if(accList.size()>0)
                    update accList;
            } 
        }Catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '----->Line Number ::' + e.getLineNumber());
        }
        
    }
    
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com

All Answers

Team NubesEliteTeam NubesElite
Hi Neeraj,
Let us take an example
//Get the count of contacts in Accounts where Mailing country = USA(Accounts lookup into contacts)
public class ContactTriggerHandler {
       public static void contactCountRollup() {
        set<id> accid = new set<id>();
        List<Contact> triggerOld = (List<Contact>)trigger.old;
        List<Contact> triggerNew = (List<Contact>)trigger.new;
        Map<Id,Contact> triggerOldMap = (Map<Id,Contact>)trigger.oldMap;
    for(Contact con : trigger.isdelete ? triggerOld : triggerNew){
        if(trigger.isupdate && triggerOldMap.get(con.id).MailingCountry != con.MailingCountry && 
           (triggerOldMap.get(con.Id).MailingCountry != null && triggerOldMap.get(con.Id).MailingCountry.EqualsIgnoreCase('USA')) 
           || (con.MailingCountry != null && con.MailingCountry.toLowerCase() == 'usa')) {
               accid.add(con.AccountId);
           } 
        else{
            accid.add(con.AccountId);
        }
        accid.add(con.AccountId);
    }
    if(accid.size()>0){
        List<account> acclist=[select id,(select id from contacts where MailingCountry='USA' )from account where id in:accid];
        for(Account acc : acclist){
            acc.Number_of_USA_Contacts__c = acc.contacts.size();
        }
            update acclist;
    }
}
}
Then you can call this method from trigger like this.
trigger ContactTrigger on Contact (after insert,after update,after delete,after undelete) {         ContactTriggerHandler.contactCountRollup();    
}

Thank You
www.nubeselite.com

Developement | Training | Consulting

Please mark this as solution if your problem resolved.
 
Deepali KulshresthaDeepali Kulshrestha
Hi Neeraj Sharma,

Greetings to you!

I have used After Insert, After Update, and Before Delete in one trigger and also I used a single method in all three cases. I have used it before delete because after deleting a record we cannot use its id that's why I used before delete. And, it's also a best practice to not use after delete always tries to use before delete.
 
Trigger
---------------------------------
trigger UpadteAccountName on Contact (after insert,after update,before delete){
    if(Trigger.isafter){
        if(Trigger.isinsert || Trigger.isupdate){
            
            ContactTriggerHandler.updateAccountName(Trigger.new,Trigger.OperationType);
        }
    }
    if(Trigger.isbefore){
        if(Trigger.isdelete){
            ContactTriggerHandler.updateAccountName(Trigger.old,Trigger.OperationType);
        }
    }
    
}


Handler class
----------------------------------------------

public class ContactTriggerHandler {
    public static void updateAccountName(List<Contact> contactList,TriggerOperation operationObject){
        try{
            String operationObj = string.valueOf(operationObject);
            
            String updatedAccName = '';
            List<String> stringList = New List<String>();
            
            List<Account> accList = new List<Account>();
            
            List<Id> contactIdSet = new List<Id>();
            
            if(contactList.size()>0){
                for(Contact contactObj : contactList){
                    if(contactObj.AccountId != Null){
                        contactIdSet.add(contactObj.id);
                    }
                }
                List<Contact> conList = New List<Contact>();
                conList = [SELECT Name,AccountId,Account.Name FROM Contact WHERE Id In :contactIdSet LIMIT 50000];
                for(Contact conatctObj : conList){
                    if(operationObj == 'AFTER_INSERT' || operationObj == 'AFTER_UPDATE'){
                        conatctObj.Account.Name = conatctObj.Account.Name + ' ' +conatctObj.Name;
                        accList.add(conatctObj.Account); 
                    }
                    else if(operationObj == 'BEFORE_DELETE'){
                        
                        stringList = conatctObj.Account.Name.split(' ');
                        stringList.remove(stringList.indexof(conatctObj.Name));
                        for(String strObj : stringList){
                            updatedAccName = updatedAccName + ' ' +strObj; 
                        }
                        conatctObj.Account.Name = updatedAccName;
                        accList.add(conatctObj.Account);
                        
                    }
                    
                } 
                if(accList.size()>0)
                    update accList;
            } 
        }Catch(Exception e){
            System.debug('Exception ::' + e.getMessage() + '----->Line Number ::' + e.getLineNumber());
        }
        
    }
    
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
This was selected as the best answer