Taken example of account and contact.
On Account object create a field to Count the number of child contacts and add it to your layout(in this example the field is Count_of_Contacts__c).Next create a Trigger on contact and simply copy and paste the below code.This will work in all DML operations such as Create ,Edit and Delete of a contact from an account and it is bulkified also 🙂
trigger UpdateCountonAccount on Contact (after insert,after update,after delete) {
set<Id> accIds = new Set<Id>();
if(trigger.isInsert || trigger.isUpdate){
for(contact con :trigger.new){
accIds.add(con.accountId);
}
}
if(trigger.isdelete){
for(contact con :trigger.old){
accIds.add(con.accountId);
}
}
Map<Id, Integer> ConCountMap = new Map<Id, Integer>();
for (AggregateResult aggRes : [
SELECT COUNT(ID) numofCons, accountId accId
FROM contact where accountId IN: accIds
GROUP BY accountId
]) {
Id accId = (Id) aggRes.get('accId');
Integer numofcons = (Integer) aggRes.get('numofCons');
ConCountMap.put(accId, numofcons);
}
if(!ConCountMap.isEmpty()){
List<account> lstAcconts = new List<account>();
List<account> lstResultAcconts = new List<account>();
lstAcconts =[select id,name from account where id IN:ConCountMap.keySet()] ;
for(account acc :lstAcconts){
if(ConCountMap.containsKey(acc.id)){
acc.Count_of_Contacts__c = ConCountMap.get(acc.id);
lstResultAcconts.add(acc);
}
}
if(!lstResultAcconts.isEmpty()){
update lstResultAcconts;
}
}
}
Let me know if you face any issues.
-
This reply was modified 7 years, 6 months ago by Shaik.