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
shekhar 46shekhar 46 

trigger to update contact with count field

On account we have total open count field, on contact we have status field of picklis LOVs as open/progress/completed. whenever contact is created /updated with status open, we need to maintain count of open contact on related parent account.
Best Answer chosen by shekhar 46
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Shekhar,

Can you try the below trigger on Contact.
trigger CountContactOnAccount on Contact (after INSERT, after UPDATE ) {
Set <Id> accountIds = new Set <Id>();
List <Account> lstAccountsToUpdate = new List <Account>();
 if(Trigger.isInsert){
    for(Contact con:trigger.new){
        if(con.status__c=='Open')
        accountIds.add(con.accountID);
    }
}
if(Trigger.isUpdate){
    for(Contact con:trigger.new){
        Contact OldContact= trigger.oldmap.get(con.id);
        if(con.status__c!=OldContact.status__c)
        accountIds.add(con.accountID);
    }
}

for(Account acc:[SELECT Id,Name,Total_Open_Count__c,(Select Id from Contacts where Status__c='Open') from Account where Id IN: accountIds]){
    Account accObj = new Account ();
    accObj.Id = acc.Id;
    accObj.Total_Open_Count__c = acc.Contacts.size();
    lstAccountsToUpdate.add(accObj);
}

UPDATE lstAccountsToUpdate;
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,