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
HARSHIL U PARIKHHARSHIL U PARIKH 

Counting Number of contcts on Account via trigger: Everything works accept that trigger always counts one record less..

Hello Developers!

I have a trigger on contct which counts number of contact record as rollup on account
Trouble: is that when I insert new contact then total_contacts__c on account becomes 0 then when I enter second contact it becomes 1 and so on..
At the end of the day if I have 5 contacts then it will show up as 4.
trigger:
Trigger ContacstTotalCount On Contact(Before Insert, Before Update, After Delete, After Undelete){
    
    Set<ID> AccountIds = New Set<ID>();
    
    If(Trigger.IsInsert || Trigger.IsUpdate || Trigger.IsUndelete){
        For(Contact C:Trigger.New){
            AccountIds.add(C.AccountID);
        }
    }
    If(Trigger.IsDelete){
        For(Contact C:Trigger.Old){
            AccountIds.add(C.AccountID);
        }
    }
    
    List<Account> AccountListToUpdate = New List<Account>();
    
    For(Account a: [Select Id, total_contacts__c, (Select Id FROM Contacts) FROM Account WHERE ID IN :AccountIds]){
        
        a.total_contacts__c = a.contacts.size();
        AccountListToUpdate.add(a);
    }
    try{
    Update AccountListToUpdate;
    }
    Catch(Exception E){
    System.Debug('Thrown Exception is: ' + E.getMessage());
    }
    
}

Thank you for the help!
Best Answer chosen by HARSHIL U PARIKH
HARSHIL U PARIKHHARSHIL U PARIKH
It working fine now.
I was putting this trigger on 
Trigger ContacstTotalCount On Contact(Before Insert, Before Update, After Delete, After Undelete)

But I guess it should be ,
 
Trigger ContacstTotalCount On Contact(After Insert, After Update, After Delete, After UnDelete)
Thank you guys anyway!