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
GtennentGtennent 

Bulk Apex Triggers Help

I'm trying to complete the Bulk Apex Triggers challenge. I understand what needs to be done, but I don't know how to do it. Also, I'm getting the very helpful error "Executing against the trigger does not work as expected."

The directions are:
  • To complete this challenge, you need to add a trigger for Opportunity. The trigger will add a task to any opportunity inserted or updated with the stage of 'Closed Won'. The task's subject must be 'Follow Up Test Task'.
  • The Apex trigger must be called 'ClosedOpportunityTrigger'
  • With 'ClosedOpportunityTrigger' active, if an opportunity is inserted or updated with a stage of 'Closed Won', it will have a task created with the subject 'Follow Up Test Task'.
  • To associate the task with the opportunity, fill the 'WhatId' field with the opportunity ID.
  • This challenge specifically tests 200 records in one operation.
Here's my code:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    List<Task> newTasks = new List<Task>();
    
    for(Opportunity opp : [SELECT Id, Name, StageName FROM Opportunity WHERE StageName = 'Closed Won' AND Id in :Trigger.new]){
    	newTasks.add(new Task(Subject = 'Follow Up Test Task.',
                             WhatId = opp.Id));
    }
    If(newTasks.size() > 0){
        insert newTasks;
    }    

}
Where have I gone wrong, why is it wrong, and how can I fix it? Please don't just give me code that works that doesn't helpe me learn. I want to understand why the code works, and how to get there from where I am. Thanks!
Dhanya NDhanya N
Hi Geoff Tennent,

You are not checking that the inserting opportunity contains StageName = 'Closed Won'. That may be the reason you are not able to complete the challenge.

Refer this code:
trigger ClosedOpportunityTrigger on Opportunity (before insert) 
{
    List<Task> lstTask = new List<Task>();
  if(Trigger.isInsert && Trigger.isBefore)
    {
      for(Opportunity objOpportunity : Trigger.New)  
      {
            //check opp stage Name
          if(objOpportunity.StageName == 'Closed Won')
          {
              Task objTask = new Task(Subject = 'Follow Up Test Task', WhatId = objOpportunity.Id);           
              lstTask.add(objTask);
          }
      } 
       insert lstTask;
    }
}

Thanks,
Dhanya