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;
}
}
}
Divya Chauhan (Kcloud Technologies) Forum Ambassador
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;
}
}