If the Parent & Child object is related with Master-Detail Relationship, we can easily get
the count of Child records and store it in the Parent object by using Roll-up Summary
field. But if the relation is Lookup between the Parent & Child, we don't have any other
option except writing Trigger. So for example I am taking Account & Contact object as these
are related with Lookup. So we need to Count all the Contact records and store it into
the respective Parent Account record.
Question: In Which Object should I write the Trigger?
Answer: Ofcourse the answer would be Contact object as when we are performing any
DML Operation on Contact record, the count of contact records will be affected and by
implementing a Trigger on Contact object, we can easily capture the Count and update it
to the respective Parent Account record.
So the answer is we have to implement the Trigger obviously in Child Object.
trigger totalContactsTrigger on Contact (After Insert,After Update,
After Delete,After Undelete) {
Set<Id> setAccIds = new Set<Id>();
//Using Trigger.new to get the Account Id for Insert & undelete Operation
if(Trigger.isInsert || Trigger.isUndelete){
for(Contact con : Trigger.new){
setAccIds.add(con.AccountId);
}
}
//Using Trigger.new & Trigger.old to get older & newer version of Account Id
if(Trigger.isUpdate){
for(Contact con : Trigger.new){
//Condition to check if the Account lookup field is updated or not
if(con.AccountId!=Trigger.oldMap.get(con.Id).AccountId){
setAccIds.add(con.AccountId);
setAccIds.add(Trigger.oldMap.get(con.Id).AccountId);
}
}
}
//Using Trigger.old to get the Account Id for Delete Operation
if(Trigger.isDelete){
for(Contact con : Trigger.old) {
setAccIds.add(con.AccountId);
}
}
List<Account> accList=new List<Account>();
for(Account acc :[Select id,Total_Contacts__c ,(Select id from contacts) from
Account where Id in : setAccIds]){
acc.Total_Contacts__c = acc.contacts.size();
accList.add(acc);
}
if(!accList.isEmpty()){
update accList;
}
}
what is AccountID??
ReplyDeleteGreat blog Salesforce online training
ReplyDelete