
8 answers
I have updated the below in trigger1) Added update and Delete event2) Added trigger.old for Delete event3) Added Null Check Please try below code.
Please let us know if this will help youThanksAmit Chaudharytrigger NumberOfContacts on Contact ( after delete, after insert, after update )
{
Set<Id> accountIds = new Set<Id>();
if(Trigger.isDelete)
{
for(Contact c : trigger.old)
{
accountIds.add(c.AccountId);
}
}
else
{
for(Contact c : trigger.new)
{
accountIds.add(c.AccountId);
}
}
if(accountIds.size() > 0 )
{
list<account> accLst = new list<account>();
for(Account objAcc: [select id,No_of_Associated_Contacts__c,(select id from contacts) from account where id In : accountIds])
{
objAcc.No_of_Associated_Contacts__c = objAcc.contacts.size();
accLst.add(objAcc);
}
if(accLst.size() > 0 )
{
update accLst;
}
}
}