For Example Contact in my Child object and Account In my Parent Object.
trigger countTotalContactInAccount on Contact(after insert,after update,after delete){
set<Id> accountIDSet = new set<Id>();
list<Account> accountUpdateList = new list<Account>();
if(trigger.isInsert ){
for(Contact c:trigger.new){
accountIDSet.add(c.AccountID);
}
if(trigger.isDelete || trigger.isUpdate){
for(Contact c:trigger.old){
accountIDSet.add(c.AccountID);
}
}
list<Account> accountList = [SELECT id,name,(SELECT id from Contacts) from Account where ID IN : accountIDSet];
for(Account a:accountList){
a.Total_contacts__c = a.contacts.size();
accountUpdateList.add(a);
}
update accountUpdateList;
}
NOTE:- Total_contacts__c is a field(DataType - Number) in Account object which store total number of Contacts in a Account.
trigger countTotalContactInAccount on Contact(after insert,after update,after delete){
set<Id> accountIDSet = new set<Id>();
list<Account> accountUpdateList = new list<Account>();
if(trigger.isInsert ){
for(Contact c:trigger.new){
accountIDSet.add(c.AccountID);
}
if(trigger.isDelete || trigger.isUpdate){
for(Contact c:trigger.old){
accountIDSet.add(c.AccountID);
}
}
list<Account> accountList = [SELECT id,name,(SELECT id from Contacts) from Account where ID IN : accountIDSet];
for(Account a:accountList){
a.Total_contacts__c = a.contacts.size();
accountUpdateList.add(a);
}
update accountUpdateList;
}
NOTE:- Total_contacts__c is a field(DataType - Number) in Account object which store total number of Contacts in a Account.
And the code doest work for update!
ReplyDeletewhat will be the query if the objects are custom objects
ReplyDeleteI can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. word counter
ReplyDeletei tried same code for Lead & Event Object. Counts get updated if we enter any Event. But if i delete any Event, Count is not decreasing
ReplyDelete