Skip to main content
Dilip Kulkarni a posé une question dans #Apex
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.
4 réponses
  1. 15 juin 2017, 06:57
    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
0/9000