/* Name:UpdateParentTotalField
* Description: This trigger will calculate the sum of child records field values and update in its parent object record field. it will fire
* on both insert and update event.
*/
trigger UpdateParentTotalField on TestChild__c (after insert,after update) {
set<id> prentsIds=new set<id>();
if(Trigger.isInsert || Trigger.isUpdate){
for(TestChild__c tc:Trigger.new){
prentsIds.add(tc.TestParent__c);
}
}
list<TestParent__c> parentList=new List<TestParent__c>();
for(TestParent__c tp:[select id,Total_No__c,(select id,No__c from TestChilds__r) from TestParent__c where id IN:prentsIds]){
TestParent__c obj=new TestParent__c();
obj.id=tp.Id;
for(TestChild__c tc:tp.TestChilds__r){
if( obj.Total_No__c==null){
obj.Total_No__c=0;
}
obj.Total_No__c+=tc.No__c;
}
parentList.add(obj);
}
if(parentList.size()>0){
try{
update parentList;
}
catch(DMLException e){
system.debug('Exception has occured! ' +e.getMessage());
}
}
}
* Description: This trigger will calculate the sum of child records field values and update in its parent object record field. it will fire
* on both insert and update event.
*/
trigger UpdateParentTotalField on TestChild__c (after insert,after update) {
set<id> prentsIds=new set<id>();
if(Trigger.isInsert || Trigger.isUpdate){
for(TestChild__c tc:Trigger.new){
prentsIds.add(tc.TestParent__c);
}
}
list<TestParent__c> parentList=new List<TestParent__c>();
for(TestParent__c tp:[select id,Total_No__c,(select id,No__c from TestChilds__r) from TestParent__c where id IN:prentsIds]){
TestParent__c obj=new TestParent__c();
obj.id=tp.Id;
for(TestChild__c tc:tp.TestChilds__r){
if( obj.Total_No__c==null){
obj.Total_No__c=0;
}
obj.Total_No__c+=tc.No__c;
}
parentList.add(obj);
}
if(parentList.size()>0){
try{
update parentList;
}
catch(DMLException e){
system.debug('Exception has occured! ' +e.getMessage());
}
}
}
This comment has been removed by the author.
ReplyDeleteA septic system is an underground chamber made of field design for installs tank through which domestic wastewater flows for basic treatment. Services for sewerage systems of all shapes and sizes - For More Information Visit Here -- field design
ReplyDeletedo you have a test class for this to get the coverage?
ReplyDeleteHello Arun, Can you please share the structure of your parent and child objects. What is TestChilds__r in your code.
ReplyDelete