+ Start a Discussion
Kunal Purohit 4Kunal Purohit 4 

How to write trigger to update count at Account whenever Contact is created/Updated

Hello All,
I am new to developmennt. 
We have Number field on Account called Open Contact Count and on Contact we have Status field picklist values as Open In Progress and Completed. Whenever any contact is created/updated with Status as Open related to Account, we need to maintain count of Open contact on related Account. I have written trigger for same but not working. Please give your valuable suggestions.
trigger ChildCount on Contact (after insert,after delete,after update,after undelete) {
     set<id> accid=new set<id>();
    if(trigger.isInsert|| trigger.IsUpdate|| trigger.isUndelete)
    {
        for(Contact con:trigger.new)
        {
            accid.add(con.AccountId);
        }
    }

    if(trigger.isDelete|| trigger.IsUpdate)
    {
        for(Contact Con: trigger.old)
        {
            accid.add(con.AccountId);
        }
    }
    
   list<Account> aclist=[select id, Open_Contact_Count__c,(Select id from Contacts) from Account where id in: accid];

 

List<Account> acupdate=new list<Account>();
   
    for(Account acc: aclist)
    {
        
       list<contact> clist= acc.Contacts;
       Account a1=new Account();
       Contact c1=new Contact();
      
               a1.Id=acc.Id;
            a1.Open_Contact_Count__c = clist.size();
       
           acupdate.add(a1);
      
    }
            update acupdate;
    }

 
Best Answer chosen by Kunal Purohit 4
Andrew GAndrew G
Simplify shoud sort things
trigger ChildCount on Contact (after insert, after update, after delete, after undelete) {
    Set<Id> accid=new Set<Id>();
    if(Trigger.isInsert|| Trigger.isUpdate|| Trigger.isUndelete){
        for(Contact con:Trigger.new){
            accid.add(con.AccountId);
        }
    }

    if(Trigger.isDelete|| Trigger.isUpdate){
        for(Contact Con: Trigger.old){
            accid.add(Con.AccountId);
        }
    }

//when we query the Accounts, get the Open Contacts
// *** change your status field name as required *****
    List<Account> aclist=[SELECT Id,(SELECT Id FROM Contacts WHERE StatusField= 'Open') FROM Account WHERE Id IN: accid];

//Now we have a simple loop as each Account will have the associated Open contacts
    for(Account acc: aclist){
        acc.Number_of_Contacts__c = acc.Contacts.size();
    }
    update aclist;

}

cheers
 

All Answers

Andrew GAndrew G
Simplify shoud sort things
trigger ChildCount on Contact (after insert, after update, after delete, after undelete) {
    Set<Id> accid=new Set<Id>();
    if(Trigger.isInsert|| Trigger.isUpdate|| Trigger.isUndelete){
        for(Contact con:Trigger.new){
            accid.add(con.AccountId);
        }
    }

    if(Trigger.isDelete|| Trigger.isUpdate){
        for(Contact Con: Trigger.old){
            accid.add(Con.AccountId);
        }
    }

//when we query the Accounts, get the Open Contacts
// *** change your status field name as required *****
    List<Account> aclist=[SELECT Id,(SELECT Id FROM Contacts WHERE StatusField= 'Open') FROM Account WHERE Id IN: accid];

//Now we have a simple loop as each Account will have the associated Open contacts
    for(Account acc: aclist){
        acc.Number_of_Contacts__c = acc.Contacts.size();
    }
    update aclist;

}

cheers
 
This was selected as the best answer
AbhishekAbhishek (Salesforce Developers) 
You can also Use Below code


trigger ContactSumTrigger on Contact (After insert, After delete, After undelete) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Contact c : Trigger.Old){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
    }
    System.debug('#### parentIdsSet = '+parentIdsSet);
    List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);
    FOR(Account acc : accountList){
        List<Contact> contactList = acc.Contacts;
        acc.Number_of_Contacts__c = contactList.size();
        accountListToUpdate.add(acc);
    }
    try{
        update accountListToUpdate;
    }catch(System.Exception e){
        
    }
}

It might help you.