[SalesForce] Relating a task when an opportunity is updated. Before or After Update trigger

I am confused about using a Before or After Update trigger. The scenario is that I want to create a new task and relate it to an opportunity when it's updated with a Stage = 'Closed Won'.

From what I've read so far, you always need to use After Update trigger in such cases. But what if I use a before update trigger? I do have the opp Id in the database and I can use it to associate it to the newly created task. When the opp is saved , the task will be created as well. Am I missing something here in my logic?

trigger ClosedOpportunityTrigger on Opportunity (after insert, before update) {

//Create a list to hold all opportunities for which tasks need to be created
List<Opportunity> oppList = new List<Opportunity>();

for(Opportunity opp: Trigger.new) {

    if(Trigger.isInsert)    {
        if(opp.StageName=='Closed Won') {
            oppList.add(opp);
        }
    }

       //Make sure trigger only works on updated Opportunities 
       where old value != new value
       else {

        Opportunity oldOpp  = Trigger.oldMap.get(opp.Id);
        Boolean oldOppIsWon = oldOpp.StageName.equals('Closed Won');
        Boolean newOppIsWon = opp.StageName.equals('Closed Won');

        if(!oldOppIsWon && newOppIsWon) {

            oppList.add(opp);
        }
    }

  }

List<Task> taskList = new List<Task>();
for(Opportunity opp :oppList) {

    Task t        = new Task();
    t.WhatId      = opp.Id;
    t.Subject     = 'Follow up test task';
    t.Priority    = 'Normal';
    t.Status      = 'Not Started';
    taskList.add(t);
}

insert taskList;

}

Best Answer

You can absolutely use an before trigger for that and it will work. That said, I typically leave the before trigger to the simpler functionality. IMO, updates to and validations against the records being acted on should happen in the before trigger, most everything else like cross object logic and callouts/emails/etc. should happen after. But there is nothing that says you can't create records before if you desire.

Related Topic