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
DipthiDipthi 

Handler class update event : Trigger.new & Trigger.Old has different logic

Can some one help me out with Handler class (Update). When I go to Account -> Go to related Contact & update to a different Account. Account field 'Total no of Contacts' should be decremented. Can any one help me with UPDATE in my handler class.

This is my Trigger : 

trigger ContactsTotalDisplayOnAccount on Contact (after insert, after update, after delete, after undelete) {
contactHandler Handler = new contactHandler();
 
  if(Trigger.isAfter && Trigger.isInsert){
        Handler.countContacts(Trigger.new,null);
    }
    
    if(Trigger.isAfter && Trigger.isUpdate){
        Handler.countContacts(Trigger.new, Trigger.Old);

    }
    
    if(Trigger.isAfter && Trigger.isDelete){
        Handler.countContacts(Trigger.old,null);
    }
    
    if(Trigger.isAfter && Trigger.isUndelete){
        Handler.countContacts(Trigger.new,null);
    }
}

My Handler Class:

public class ContactHandler {
    
    List<account> accList = new List<Account>();    
    Set<Id> accId = new Set<Id>();                    
    
    public void countContacts (List<Contact> newList, List<Contact> updateList) {  
        for(Contact con : newList) {
            System.debug(con);
            if(con.AccountId != null) {
/* Where can I add this condition :  (con.AccountId != Trigger.oldMap.get(con.id).AccountId) ){    */
               accId.add(con.AccountId); 
               System.debug(accId); 
            }
        }
        for(Account acc : [Select Name,Id,Total_Number_of_Contacts__c,(Select Id from Contacts)
                       from Account Where Id IN :accId])  {
            System.debug(acc);               
            Account acts = new account();
            acts.Id = acc.Id;
            acts.Total_Number_of_Contacts__c = acc.Contacts.Size();
            accList.add(acts); 
            System.debug(accList);               
        }       
    update accList;        
   }

}    

 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Dipthi,

As per the description I see that you are trying to show number of contacts on account record, if so you can use the below snippet.
 
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
    //---> above handling all states which could see a contact added to or removed from an account
   
    //---> on delete we use Trigger.Old, all else, Trigger.new
    List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;

    //---> the Set class rocks for finding the unique values in a list
    Set<Id> acctIds = new Set<Id>();
   
    for (Contact c : contacts) {
     //yes, you can have a contact without an account
        if (c.AccountId != null) {
            acctIds.add(c.AccountId);
        }
    }
   
    List<Account> acctsToRollup = new List<Account>();
    
    //****** Here is the Aggregate query...don't count in loops, let the DB do it for you*****
    for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                               FROM Contact 
                               WHERE AccountId in: acctIds 
                               GROUP BY AccountId]){
        Account a = new Account();
        a.Id = (Id) ar.get('AcctId'); //---> handy trick for updates, set the id and update
        a.Contact_Count__c = (Integer) ar.get('ContactCount');
        acctsToRollup.add(a);
    }
    
    //----> probably you'll want to do a little more error handling than this...but this should work. 
    update acctsToRollup;

}

reference: https://developer.salesforce.com/forums/?id=906F0000000AcdaIAC

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
DipthiDipthi

Hi AnuTej,

Thaks for the reply. This will only work good for Insert,Delete & Update (Partially)
In Update, we have two scenarios : Ur code will work for scenario 2 but not for 1
1. Update Previous Account (Decrement 1 from 'Total no of Contacts' field)
2. Update new Account (Increment 1 to 'Total no of Contacts' field)

I am new to developing. Plz look at my updated Trigger & Handler and help me out to fix my update for Scenario 1. 

trigger ContactsTotalDisplayOnAccount on Contact (after insert, after update, after delete, after undelete) {
    
    contactHandler Handler = new contactHandler();
    if(Trigger.isAfter && Trigger.isInsert){
        Handler.countContacts(Trigger.new,null);
    }
    
    if(Trigger.isAfter && Trigger.isUpdate){
        Handler.countContacts(Trigger.new, Trigger.OldMap);
    }
    

    if(Trigger.isAfter && Trigger.isDelete){
        Handler.countContacts(Trigger.old,null);
    }
    
    if(Trigger.isAfter && Trigger.isUndelete){
        Handler.countContacts(Trigger.new,null);
    }
}
    

public class ContactHandler {
    
    List<account> accList = new List<Account>();    
    Set<Id> accId = new Set<Id>();                    
    
    public void countContacts (List<Contact> newList, Map<Id,Contact> oldMap) {   
        System.debug(oldMap);
        System.debug(newList);
        
        for(Contact con1 : newList) {
            System.debug(con1);
            if(con1.AccountId != null) { 
               accId.add(con1.AccountId); 
               System.debug(accId); 
            } 
           
            if(con1.AccountId != oldMap.get(con1.Id).AccountId) {
               accId.add(con1.AccountId);  // Increment the value of 'Total no of Contacts' on new Account
               System.debug(accId);
               // Decrement the value of 'Total no of Contacts' on old Account
               // Compare Trigger.oldMap.get(id) with Trigger.newMap.get(id) -- trigger.newMap.keySet
            }
        } 

        
        for(Account acc : [Select Name,Id,Total_Number_of_Contacts__c,(Select Id from Contacts)
                       from Account Where Id IN :accId])  {
            System.debug(acc);               
            Account acts = new account();
            acts.Id = acc.Id;
            acts.Total_Number_of_Contacts__c = acc.Contacts.Size();
            acts.Description = 'Total Contacts on this Account = ' +acc.Contacts.Size();
            accList.add(acts); 
            System.debug(accList);               
        }       
    update accList;        
   }

}