Search code examples
databasesalesforceapexsalesforce-lightningsoql

Salesforce How to update a roll-up summary field on parent table from inside method that gets triggered when child is persisted


I created a Commission object with field called commission_amount__c, This object has a master detail relationship with Contact. Contact Has a sum up field called Total_Commission__c which sums up all commission amounts from Commissions related to each Contact. I've put a trigger on Commission which calls the method updatePrimary. I want to get each persons total commission but when I query this inside updatePrimary I get the old value in the sumup field(total_commission) and not the new value with the new commission amount added. it hasn't summed up yet. Some help would be very much appreciated if possible.

trigger UpdatePrimaryTrigger on Commission__c (after insert, after update) {
    
    
        for(Commission__c c : Trigger.New) {
            ContactHandler.updatePrimary(c);
        }
    }
public class ContactHandler {
    
    public static void updatePrimary(Commission__c comIn){ 
        
        Contact receiverOfCommission = [Select Name, Total_commission__c
                                       FROM Contact
                                       Where Id = :comIn.Contact__c];
    }

Solution

  • You're at the wrong position in the save order of execution.

    Roll-up summary fields are updated on the parent object at Step 18. after triggers are executed at Step 8.

    If you want to take action upon the update of your roll-up summary field, you will need to write a trigger on the parent object. However, if I understand your requirement correctly, you may be able to simply place a formula field on the Commission object referencing the roll-up summary field on the Contact.