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.
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.
I 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:
It was really interesting =)
Sincerely,
Mykhailo Vdovychenko
Bringing Cloud Excellence with IBVCLOUD OÜ