Skip to main content Join us at TDX in San Francisco or on Salesforce+ on March 5-6 for the Developer Conference for the AI Agent Era. Register now.

#Trailhead Challenges2,392 discussing

Hands-on challenges are the “secret sauce” of Trailhead. Before searching for solutions to superbadge challenges, review the Salesforce Certification Program Agreement and Policies.

We tried to insert Opportunity records as part of the challenge check, but the insert failed. Error: thException: OPP_INSERT | System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, ClosedOpportunityTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 00TWU0000002p852AA; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.ClosedOpportunityTrigger: line 13, column 1: []

 

I get this error on checking the Bulk Apex Trigger challenge in the Apex Triggers Badge. Reading the error, it seems the test script is inserting an opportunity with Id. Anyone else getting this error? My trigger is inserting tasks without any Id and works like a charm, even on newly created opportunity.

 

#Trailhead Challenges  #Trailhead

11 answers
  1. Jan 23, 2024, 3:31 PM

    Hi, @Yvonne Riemeijer

     

    Nothing to worry about, everything is fine. I also try to relax on weekends, but weekdays are busy with work.

    So, thank you for the provided trigger code. I ran it in my system and encountered a similar error.1.jpgI made some changes to it, and now everything is working. Please use this code, and the challenge will be completed.

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

    List<Task> tasksToCreate = new List<Task>();

    for(Opportunity oppty : Trigger.New) {

    if (oppty.StageName == 'Closed Won') {

    Task nwTask = new Task();

    nwTask.Subject = 'Follow Up Test Task';

    nwTask.WhatId = oppty.Id;

    tasksToCreate.add(nwTask);

    }

    }

    if (!tasksToCreate.isEmpty()){

    insert tasksToCreate;

    }

    }

    And, by the way, here's where the mistake was:

    It was necessary to simply write outside the loop:1.jpg2.jpg

    It was really interesting =)

     

    Sincerely,

    Mykhailo Vdovychenko

    Bringing Cloud Excellence with IBVCLOUD OÜ

0/9000

Hola buen día.    He tratado de realizar el reto pero no logro aprobarlo, ya he modificado el trigger de varias formas y no logro aprobar, ya lo he testeado por "Execute Anonymous Windows" y allí funciona bien, pero al validar el reto me dice que "Se creó una oportunidad pero no una tarea".    Esta es la versión inicial:    trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {      List<Task> tasks = new List<Task>();            for (Opportunity opp : Trigger.New) {          System.debug('##### ' + opp.StageName);          if(opp.StageName == 'Closed Won') {          tasks.add(new Task(Subject='Follow Up Test Task', WhatId=opp.Id));          }      }      System.debug('tasks ' + tasks.size());      if (tasks.size() > 0) {          insert tasks;          System.debug('tasks Inserted');      }  }    Ya la he cambiado hasta esto y no consigo que funcione:  trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {      List<Task> tasks = new List<Task>();      List<Opportunity> toProcess = null;            switch on Trigger.operationType {          when AFTER_INSERT {              toProcess = Trigger.New;          }          when AFTER_UPDATE {              toProcess = [SELECT Id, StageName FROM Opportunity WHERE Id IN :Trigger.New /*AND StageName = 'Closed Won'*/];          }      }            for (Opportunity opp : toProcess) {          System.debug('##### ' + opp.StageName);          if(opp.StageName == 'Closed Won') {          Task ta = new Task(Subject='Follow Up Test Task', WhatId=opp.Id);              //tasks.add(new Task(Subject='Follow Up Test Task', WhatId=opp.Id));          tasks.add(ta);          }      }      System.debug('tasks ' + tasks.size());      if (tasks.size() > 0) {          insert tasks;          System.debug('tasks Inserted');      }  }        Agradezco cualquier ayuda.    Saludos.   

4 answers
  1. Feb 17, 8:12 PM

    Hi, @Arnab Mukherjee

    ,  

     

    Thank you very much for your attention. It worked now, I just had to log out and log back in, and it worked without any problems. It is likely that something was wrong that was only corrected with the data from a new session. 

     

    Thank you!!!

0/9000

When I test my code through the "Execute Anonymous Window", it seems to work fine.

When I check the challenge, I get this error.  I don't know what it means.

Developer script exception from State of Wyoming : ClosedOpportunityTrigger : ClosedOpportunityTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 00Tbm000004HLlhEAG; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.ClosedOpportunityTrigger: line 23, column 1

 

Challenge

Create a Bulk Apex trigger

Create a bulkified Apex trigger that adds a follow-up task to an opportunity if its stage is Closed Won. Fire the Apex trigger after inserting or updating an opportunity.

  • Create an Apex trigger:
    • Name: ClosedOpportunityTrigger
    • Object: Opportunity
    • Events: after insert and after update
    • Condition: Stage is Closed Won
    • Operation: Create a task:
      • Subject: Follow Up Test Task
      • WhatId: the opportunity ID (associates the task with the opportunity)
    • Bulkify the Apex trigger so that it can insert or update 200 or more opportunities

This is my code:

 

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

    List<Task> taskList = new List<Task>();

    

    List<Opportunity> toProcess = null;

    

    switch on Trigger.operationType {

        when AFTER_INSERT {

        // All inserted Opportunity will need the Opportunity

            toProcess = Trigger.New;

        }

        // Check if the status has changed to Closed Won

        when AFTER_UPDATE {

            toProcess = [SELECT Id,StageName FROM Opportunity

                         WHERE Id IN :Trigger.New];

        }

    }

    for (Opportunity opp : toProcess) {

        // Add a default task for this opportunity

        system.debug('Opportunity: ' + opp.Id + 'StageName: ' + opp.StageName);

        If (opp.StageName == 'Closed Won') {

          taskList.add(new Task(Subject = 'Follow Up Test Task', WhatId = opp.Id));

    }

    if (taskList.size() > 0) {

        system.debug(taskList);

        insert taskList;

    }

  }

}

 

#Trailhead Challenges

3 answers
  1. Divya Chauhan (Kcloud Technologies) Forum Ambassador
    Jan 16, 6:26 AM

    Hello@Marlene Meiring,

    • Make sure you have saved the code
    • try,

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

    List<Task> taskList = new List <task>();

    for(Opportunity opp : Trigger.New){

    if(opp.StageName == 'Closed Won'){

    taskList.add(new Task(Subject = 'Follow Up Test Task', WhatId = opp.Id));

    }

    }

    if(taskList.size()>0){

    insert taskList;

    }

    }

0/9000

 whats going on is im stuck on the bulk apex triggers and getting a errror and trying to fix it 

 

 Challenge not yet complete in Playful Badger Playground

The trigger ClosedOpportunityTrigger is using events in the 'before' context. Make sure to use after insert and after update. 

 

#Trailhead Challenges

3 answers
0/9000

When I check my challenge - I get the error message The trigger ClosedOpportunityTrigger is using events in the 'before' context. Make sure to use after insert and after update.

 

Here is my trigger below - So I don't understand why it's saying I'm using before context.  I've deleted this trigger once and re-made it only to receive the same error on submission 

 

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

List<Task> taskToUpdate = new List<Task>();

//get Opp Ids from Closed Won Opps

for(Opportunity opp : [SELECT ID FROM Opportunity WHERE StageName = 'Closed Won' IN :Trigger.New]) {

//create follow up task against IDS that are stored in opp variable

taskToUpdate.add(new Task(Subject = 'Follow up Test Task',

WhatID=opp.ID));

}

insert taskToUpdate;

}

2 answers
0/9000
2 answers
  1. Nov 6, 2024, 9:18 PM

    Hi ,

     

    I think the settings for the previous challenge remain. Please deactivate.

     

    Setup-->Object Manager --> Choose (Opportunity)-->Fields-->Edit(Discount__c) and uncheck required

0/9000
5 answers
  1. Oct 30, 2024, 12:18 PM

    Hello@Samiksha Bokade,

    Please try,

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

    List<Task> taskList = new List<Task>();

    for(Opportunity opp : [SELECT Id, StageName FROM Opportunity WHERE StageName='Closed Won' AND Id IN : Trigger.New]){

    taskList.add(new Task(Subject='Follow Up Test Task', WhatId = opp.Id));

    }

    if(taskList.size()>0){

    insert tasklist;

    }

    }

    https://trailhead.salesforce.com/trailblazer-community/feed/0D54V00007T4OdESAV

0/9000