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
Dilip Kulkarni 12Dilip Kulkarni 12 

trigger to update value

Hi,
I have one field 'total no. of contacts' on account detail page.I want to update that no. whenever contact is deleted.
What will be the the trigger code for the same. 
Kindly help.

Regards.
Best Answer chosen by Dilip Kulkarni 12
Sam AroraSam Arora
Try this One !!! 
trigger CountContact on Contact(after insert,after delete) {
    Map<Id, List<Contact>> AcctContactList = new Map<Id, List<Contact>>();
    Set<Id> AcctId = new Set<Id>();   
    List<Account> AcctList = new List<Account>();
    List<Contact> ConList = new List<Contact>();
   
    if(trigger.isInsert)  {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId)){
                AcctId.add(Con.AccountId); 
            }  
        } 
    }  
    if(trigger.isDelete) {
        for(Contact Con : trigger.Old) {
            AcctId.add(Con.AccountId);    
        } 
    }          
   
    if(AcctId.size() > 0){
        ConList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN : AcctId];
       
        for(Contact Con : ConList) {
            if(!AcctContactList.containsKey(Con.AccountId)){
                AcctContactList.put(Con.AccountId, new List<Contact>());
            }
            AcctContactList.get(Con.AccountId).add(Con);     
        }                          
         
        AcctList = [SELECT Contact_Count__c FROM Account WHERE Id IN : AcctId];
        for(Account Acc : AcctList) {
            List<Contact> ContList = new List<Contact>();
            ContList = AcctContactList.get(Acc.Id);
            Acc.Contact_Count__c  = ContList.size();
        }   
                     
        update AcctList;   
    }
}
Replace the field api name in account as per your field name .
Thanks Shanky Munjal

All Answers

ManojjenaManojjena
Hi Dillip,

Try with below code !!
 
trigger NumOfContacts  on Contact ( after insert,after delete,after undelete) {
     Set<Id> accIdSet=new Set<Id>();
     List<Contact> contactToUpdate=new List<Contact>();
     if(Trigger.isInsert || Trigger.isUndelete){
        for(Contact con : Trigger.new){
            if(con.AccountId != null)
                accIdSet.add(con.AccountId);     
        }
    }If(Trigger.isDelete){
       for(Contact con : Trigger.old){
            if(con.ContactId != null)
                accIdSet.add(con.AccountId);     
        }
    }
   for(AggregateResult res : [SELECT count(Id)can,AccountId FROM Contact WHERE AccountId IN :accIdSet group by AccountId]) {
          contactToUpdate.add(new Contact(Id=(Id)res.get('AccountId'),Number_of_Contacts__c=(Integer)res.get('can')));
    }
    try{
      update contactToUpdate;
    }catch(DmlException de){
      System.debug(de);
    }
}

Replace the field api name in account as per you rfield name .

Let me know if it helps !!
Thanks 
Manoj 
Sam AroraSam Arora
Try this One !!! 
trigger CountContact on Contact(after insert,after delete) {
    Map<Id, List<Contact>> AcctContactList = new Map<Id, List<Contact>>();
    Set<Id> AcctId = new Set<Id>();   
    List<Account> AcctList = new List<Account>();
    List<Contact> ConList = new List<Contact>();
   
    if(trigger.isInsert)  {
        for(Contact Con : trigger.New) {
            if(String.isNotBlank(Con.AccountId)){
                AcctId.add(Con.AccountId); 
            }  
        } 
    }  
    if(trigger.isDelete) {
        for(Contact Con : trigger.Old) {
            AcctId.add(Con.AccountId);    
        } 
    }          
   
    if(AcctId.size() > 0){
        ConList = [SELECT Id, AccountId FROM Contact WHERE AccountId IN : AcctId];
       
        for(Contact Con : ConList) {
            if(!AcctContactList.containsKey(Con.AccountId)){
                AcctContactList.put(Con.AccountId, new List<Contact>());
            }
            AcctContactList.get(Con.AccountId).add(Con);     
        }                          
         
        AcctList = [SELECT Contact_Count__c FROM Account WHERE Id IN : AcctId];
        for(Account Acc : AcctList) {
            List<Contact> ContList = new List<Contact>();
            ContList = AcctContactList.get(Acc.Id);
            Acc.Contact_Count__c  = ContList.size();
        }   
                     
        update AcctList;   
    }
}
Replace the field api name in account as per your field name .
Thanks Shanky Munjal
This was selected as the best answer
Dilip Kulkarni 12Dilip Kulkarni 12
Hi Manoj,
Thanks for your kind response. I want trigger only when contact is deleted. Is your trigger only for delete operation? If not please modify.
Dilip Kulkarni 12Dilip Kulkarni 12
Hi Shanky,
Thanks.
Your trigger is working fine, but I am getting one error when I am trying to delete all contacts ( means there will be no contacts) as follows.
How to solve this?

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger CountContact caused an unexpected exception, contact your administrator: CountContact: execution of AfterDelete caused by: System.NullPointerException: Attempt to de-reference a null object: ()".