function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ryanschierholzryanschierholz 

Can you help me optimize my Trigger?

Hey fam, I have a trigger that runs after an Closing is complete/closed that will sum the other Closings volume and commission. Then, cycle through the Goals the User has added for this year, and update their progress towards their goal. This is one of my first Triggers, and I am obviously new to the game. I found some guides on bulkifying the code, but most of those were for single object or related object triggers. These two objects are unrelated. Is there anything I can do to optimize this? Thanks! 
trigger UpdateGoals on pba__Closing__c (after update, after insert) {
    
    //	loop through each closing that is updated/insert.
    for(pba__Closing__c c : Trigger.New)
    {
        //	If the closing is CLOSED, then do some work. 
        if (c.Closing_Status__c == 'Closed'){
            
            String Owner = c.OwnerId;
            Date d = c.ClosingDate__c;
            Integer yr = d.year();

            //	get the sum of fields on the Closed closings of the closed date of the closing, by the owner. 
            AggregateResult[] getSums = [SELECT SUM(Sales_Volume__c) sales_volume, 
                                         SUM(Agent_True_Gross_Commission_Total__c) sum_commissions,
                                      
                                         FROM pba__Closing__c
                                         WHERE Closing_Year__c = :yr
                                         AND Closing_Status__c = 'Closed'
                                         AND OwnerId = :Owner
                                        ];  

            //	loop through each GOAL of the associated user and year
            for (Goal__c g : [SELECT Id, Name, Actual_Value__c, OwnerId, Goal_Field__c
                              FROM Goal__c
                              WHERE OwnerId = :Owner
                              AND Year__c = :yr ]) 
            {
                //	CASE through Goal_Field__c to update 
                switch on g.Goal_Field__c {
                    when 'Sales_Volume' {
                        g.Actual_Value__c = Integer.valueOf(getSums[0].get('sales_volume'));
                        update g;
                    }
                   
                    when 'Net_Commission' {
                        g.Actual_Value__c = Integer.valueOf(getSums[0].get('sum_commissions'));
                        update g;
                    }
                    
                    
                }                
            }
        }
    }
}