4 risposte
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