A blog about Salesforce CRM Configuration and development

Saturday, 23 June 2018

Apex Trigger: Calculate the sum of child records field value and update in its parent object record field.

/* 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());
        }
    }
}
Share:

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. A 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

    ReplyDelete
  3. do you have a test class for this to get the coverage?

    ReplyDelete
  4. Hello Arun, Can you please share the structure of your parent and child objects. What is TestChilds__r in your code.

    ReplyDelete

Trailhead Profile


Follow by Email

Total Pageviews

Followers

Popular Posts

Powered by Blogger.

Contact form

Name

Email *

Message *