Trigger to update parent record when any child record is updated.
When rollup summary cannot be used since the objects do not have a Master-Detail relationship, try the below:
trigger rollupKind on Child_Object__c (after insert, after delete, after update) {
if(Trigger.isInsert){
try {
for (Child_Object__c child : Trigger.new){
Parent_Object__c parent = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :child.Parent_Lookup__c];
List<Child_Object__c> lChild = [SELECT Id, Amount__c FROM Child_Object__c WHERE Parent_Lookup__c = :parent.Id];
for(Child_Object__c amChild : lChild) {
amount += amChild.Amount__c;
}
parent.Sum_Field__c = amount;
update parent;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isAfter) {
if(Trigger.isUpdate){
try {
for (Child_Object__c child : Trigger.old){
Parent_Object__c parent = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :child.Parent_Lookup__c];
List<Child_Object__c> lChild = [SELECT Id, Amount__c FROM Child_Object__c WHERE Parent_Lookup__c = :parent.Id];
for(Child_Object__c amChild : lChild) {
amount += amChild.Amount__c;
}
parent.Sum_Field__c = amount;
update parent;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isDelete){
try {
for (Child_Object__c child : Trigger.old){
Parent_Object__c parent = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :child.Parent_Lookup__c];
List<Child_Object__c> lChild = [SELECT Id, Amount__c FROM Child_Object__c WHERE Parent_Lookup__c = :parent.Id];
for(Child_Object__c amChild : lChild) {
amount += amChild.Amount__c;
}
parent.Sum_Field__c = amount;
update parent;
}
} catch (Exception e) {
System.debug(e);
}
}
}
}
x
Comments
Post a Comment