Write field update logic in before or after trigger

after-triggerapexbefore-triggertrigger

I have to perform below logic to update opportunity status based on opportunity's Account's trial__c field on insert of opportunity.

For(Opportunity opp : trigger.new)
     { 
       If(opp.Account.trial__c == 'service') 
       {
         opp.status__c  = 'Closed'; 

       }
       
     } 

however trigger.new doesnt contain related object field so we will need to query it from opportunity and for that we would need id. So above logic cannot be performed in before trigger of opprotunity and doing this logic in after trigger of opportunity wont be best practice as we will be updating field of opportunity record in opportunity after trigger.

What can be the best way to implement this functionality.

Best Answer

Field updates should always go in the before context. Putting them after requires further DML, which has a host of complications. If you need to query for related records, you can query those tables by Id instead.

Set<Id> accountIds = new Set<Id>();
for (Opportunity record : trigger.new)
    accountIds.add(record.AccountId);
Map<Id, Account> accounts = new Map<Id, Account([
    SELECT Trial__c FROM Account WHERE Id IN :accountIds
]);
for (Opportunity record : trigger.new)
{
    if (accounts.get(record.AccountId)?.Trial__c == 'Some Value')
    {
        // logic here
    }
}

You may also want to look into some best practices like Trigger Handler pattern, and Filter Layer as well.