The following trigger is a good example of a child to parent trigger : trigger TRIGGERNAME on Child_Object__c (after insert, after delete, after update) {
if(Trigger.isInsert){ try { for (Child_Object__c co : Trigger.new){ Parent_Object__c po = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :co.Parent_Lookup__c];
if(Trigger.isAfter) { if(Trigger.isUpdate){ try { for (Child_Object__c co : Trigger.old){ Parent_Object__c po = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :co.Parent_Lookup__c];
if(Trigger.isDelete){ try { for (Child_Object__c co : Trigger.old){ Parent_Object__c po = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :co.Parent_Lookup__c];
update po; } } catch (Exception e) { System.debug(e); } } } } I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
https://developer.salesforce.com/forums/?id=906F0000000kIzEIAU
Please refer these links:
https://developer.salesforce.com/forums/?id=906F0000000DE8EIAW
https://developer.salesforce.com/forums/?id=906F0000000AvgCIAS
https://salesforce.stackexchange.com/questions/23338/trigger-to-update-parent-object-value-with-child-value
https://developer.salesforce.com/forums/?id=906F0000000kIzEIAU
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha
The following trigger is a good example of a child to parent trigger :
trigger TRIGGERNAME on Child_Object__c (after insert, after delete, after update) {
if(Trigger.isInsert){
try {
for (Child_Object__c co : Trigger.new){
Parent_Object__c po = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :co.Parent_Lookup__c];
List<Child_Object__c> l_co = [SELECT Id, Amount__c FROM Child_Object__c WHERE Parent_Lookup__c = :po.Id];
for(Child_Object__c am_co : l_co) {
amount += am_co.Amount__c;
}
po.Sum_Field__c = amount;
update po;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isAfter) {
if(Trigger.isUpdate){
try {
for (Child_Object__c co : Trigger.old){
Parent_Object__c po = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :co.Parent_Lookup__c];
List<Child_Object__c> l_co = [SELECT Id, Amount__c FROM Child_Object__c WHERE Parent_Lookup__c = :po.Id];
for(Child_Object__c am_co : l_co) {
amount += am_co.Amount__c;
}
po.Sum_Field__c = amount;
update po;
}
} catch (Exception e) {
System.debug(e);
}
}
if(Trigger.isDelete){
try {
for (Child_Object__c co : Trigger.old){
Parent_Object__c po = [SELECT Id, Sum_Field__c FROM Parent_Object__c WHERE Id = :co.Parent_Lookup__c];
List<Child_Object__c> l_co = [SELECT Id, Amount__c FROM Child_Object__c WHERE Parent_Lookup__c = :po.Id];
for(Child_Object__c am_co : l_co) {
amount += am_co.Amount__c;
}
po.Sum_Field__c = amount;
update po;
}
} catch (Exception e) {
System.debug(e);
}
}
}
}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi