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
Pierre-AlainPierre-Alain 

Error "Executing against the trigger does not work as expected."

Hi - when doing the challenge "Bulk Apex Trigger" in Trailhead I get the error message :"Executing against the trigger does not work as expected."

I have checked the name of the class, task name as mentioned in the challenge description.

I have copied the code below :

trigger ClosedOpportunityTrigger on Opportunity (before insert, before update) {
  List<Task> taskList = new List<Task>();

    //If an opportunity is inserted or updated with a stage of 'Closed Won'
    // add a task created with the subject 'Follow Up Test Task'.
    for (Opportunity opp : [SELECT Id,Name FROM Opportunity
                     WHERE Id IN :Trigger.new AND StageName = 'Closed Won']) {
       //add a task with subject 'Follow Up Test Task'.
       taskList.add(new Task(Subject='Follow Up Test Task', WhatId = opp.id ));                
  }
                          
    if (taskList.size() > 0) {
        insert taskList;
    }



Thank you
Pierre-Alain


 
Best Answer chosen by Pierre-Alain
Ravikant kediaRavikant kedia
First of all you dont need to query the records. In triggers you get those records in by Trigger.new. and if you choose your way which is wrong ( because of an extra sql query ) you need to add "Id IN Trigger.newmap.keyset()" instead of "Id IN :Trigger.new" because "Trigger.new" will return a list of Opportunity records for which it is fiered while "Trigger.newmap.keyset()" will return a set if ID.

Please select this as a best answer.

All Answers

Ravikant kediaRavikant kedia
Use below code to complete your requirement.

trigger ClosedOpportunityTrigger on Opportunity (before insert, before update) 
{
    List<Task> taskList = new List<Task>();
    
    //If an opportunity is inserted or updated with a stage of 'Closed Won'
    // add a task created with the subject 'Follow Up Test Task'.
    for (Opportunity opp : Trigger.new) 
    {
       //add a task with subject 'Follow Up Test Task'.
       if(opp.StageName == 'Closed Won')
           taskList.add(new Task(Subject='Follow Up Test Task', WhatId = opp.id ));                
    }
                          
    if (taskList.size() > 0) 
    {
        insert taskList;
    }


if my answer helps resolve your query, please select it as a 'Best Answer' so that it benefits others and helps us improve the overall quality of the forums.
 
Pierre-AlainPierre-Alain
Thanks Ravikant,

After copying/pasting your code, it worked. By comparing boths codes I can see that the difference is ( my code in italic, your code in Bold )

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

    

for (Opportunity opp : Trigger.new) 
    {
       if(opp.StageName == 'Closed Won')

           
Is there anything wrong about the code I added ( Italic ) ? I don't understand why the challenge would fail.

Thank you
Pierre-Alain
 
Ravikant kediaRavikant kedia
First of all you dont need to query the records. In triggers you get those records in by Trigger.new. and if you choose your way which is wrong ( because of an extra sql query ) you need to add "Id IN Trigger.newmap.keyset()" instead of "Id IN :Trigger.new" because "Trigger.new" will return a list of Opportunity records for which it is fiered while "Trigger.newmap.keyset()" will return a set if ID.

Please select this as a best answer.
This was selected as the best answer
Pierre-AlainPierre-Alain
ok thank for the clarifiications.
Pierre HausheerPierre Hausheer
Your code was good in the first place (the suggested if statement here is not optimised and your bulk SOQL is what is expected here) exept for the before trigger. Indeed, you should use after trigger, otherwise you won't have any value for the opportunities Id.

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

---
This is one year question old but it's showing on top of google search.
Vipul Dalal 9Vipul Dalal 9
You were not checking for old StageName if the trigger is updated.  Addting this code below as I still see this on top of google search.  Here's code that worked:

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    
    List<Task> OpTasklist = new List<Task>();
    
    // Iterate over opportunities that are in this trigger and have a stage of "Closed Won"
    for (Opportunity op: [SELECT id FROM Opportunity 
                          WHERE Id IN :Trigger.New AND
                          StageName =: 'Closed Won']) {
                              
                              if (((Trigger.IsUpdate) && (Trigger.oldMap.get(op.Id).StageName != 'Closed Won')) || 
                                  (Trigger.IsInsert)) {
                                      OpTaskList.add(new Task (Subject='Follow Up Test Task', 
                                                               WhatId = op.Id)); }          
                          }
    
    If (OpTaskList.size() > 0) { 
        Insert OpTaskList ;
    }   
}
Martin raj 4Martin raj 4
Thank you so much for the information. Very good post

https://apkmoto.com/

yowhatsapp apk (https://apkmoto.com/yowhatsapp-apk/)
sunny peddisunny peddi


Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. 
I wanted to thank you for this websites! Thanks for sharing.
https://pubg-apk.com
sunny peddisunny peddi


Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. 
I wanted to thank you for this websites! Thanks for sharing. Great websites!
https://apkfasak.com/
Filip Poverud 4Filip Poverud 4
This solution worked for me:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    List<Task> taskList = new List<Task>();
    
    for (Opportunity o : [SELECT Id FROM Opportunity WHERE StageName = 'Closed Won' AND Id IN :Trigger.New] ) {
        switch on Trigger.operationType {
            when AFTER_INSERT {
                taskList.add(new Task(Subject = 'Follow Up Test Task', WhatId = o.Id));
            }
            when AFTER_UPDATE {
                taskList.add(new Task(Subject = 'Follow Up Test Task', WhatId = o.Id));
            }
        }
    }
    
    insert taskList;
}

 
akshaya vengalaakshaya vengala
https://kingrootappx.com/ 
kingroot for pc

 This app will help you to get access to the root of your device.
 
Michael Dean 25Michael Dean 25
I Fully Agreed With VIPUL Dalal
The Code Is Right

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    
    List<Task> OpTasklist = new List<Task>();
    
    // Iterate over opportunities that are in this trigger and have a stage of "Closed Won"
    for (Opportunity op: [SELECT id FROM Opportunity 
                          WHERE Id IN :Trigger.New AND
                          StageName =: 'Closed Won']) {
                              
                              if (((Trigger.IsUpdate) && (Trigger.oldMap.get(op.Id).StageName != 'Closed Won')) || 
                                  (Trigger.IsInsert)) {
                                      OpTaskList.add(new Task (Subject='Follow Up Test Task', 
                                                               WhatId = op.Id)); }          
                          }
    
    If (OpTaskList.size() > 0) { 
        Insert OpTaskList ;
    }   
}

Thanks
Regards
Geometry Dash APK (https://geometrydashapk.co/)
nagavamsi katragaddanagavamsi katragadda
Here is my code : if you want to go with apex class 
==================Apex Class =======================
public class OpportunityApexClass {
    
    public static void opportunityTrigger(list<Opportunity> varOpportunity)
    {
        list<Task> varTask = new list<Task>();
     for(Opportunity varopp : varOpportunity)
        {
         if(varopp.StageName == 'Closed Won')
            { 
                Task varTa = New Task();
                varTa.Subject ='Follow Up Test Task';
                varTa.Status ='Not Started';
                varTa.WhatId = varopp.Id;
                 varTask.add(varTa);
            } 
        }
         insert varTask; 
    }
}

===================Trigger==========================
trigger ClosedOpportunityTrigger on Opportunity (before insert,before update) {
    
    if(Trigger.isbefore == True && Trigger.isinsert == True)
    {
        OpportunityApexClass.opportunityTrigger(Trigger.new);   
    }
    if(Trigger.isbefore == True && Trigger.isupdate == True)
    {
        OpportunityApexClass.opportunityTrigger(Trigger.new);
    }

}
Marry LaneMarry Lane
I was more than happy to uncover this great site. I need to to thank you for your time 
due to this fantastic read!! I definitely enjoyed every bit of it and I have you bookmarked 
to see new information on your blog. Text Fonts Generator (https://textfontsgenerator.blogspot.com/)
Ronnie RoyRonnie Roy
When I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I receive four emails with the exact same comment. There has to be an easy method you can remove me from that service? Kudos!
Apex Launcher (https://apexlauncherapk.com/)
Ronnie RoyRonnie Roy
I truly love your blog.. Excellent colors & theme. Did you create this website yourself? Please reply back as I’m planning to create my own personal website and would love to learn where you got this from or what the theme is called. Kudos!
Launcher Apk (https://launcherapk.com/)
Apks For FreeApks For Free
Excellent Blog! I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. 
https://www.apksforfree.com/
https://www.apksforfree.com/oreo-tv-apk/
Aftab Shaikh 8Aftab Shaikh 8
I think yowhatsapp (https://tricksground.com/yowhatsapp-apk-download/) and gbwhatsapp (https://gbmod.net/download-gbwhatsapp-apk/) are the best apps right now.
Matthias RichterMatthias Richter
Hi there
so good blod, thanks

tap here (https://swissnativecasinos.com/online-casino/zimpler)
mint winmint win
You shared a useful post and thanks for sharing this to us. The peryourhealth is an online medical billing payment portal, where the user can simply get a login, complete the entire process without facing any kind of trouble. https://peryourhealth.fun
Amlida JamesAmlida James
Hi,

Thank you for sharing such a nice post on your blog keep it up and share more. home network security solution (https://dmoat.com/)
amaya sydneyamaya sydney
Excellent solution keep it up. https://cytex.io/
sten minsten min
Online surveys are very popular at present. TellTheBell Survey helps you to take a survey in which customers give reviews to the company. After completing this survey, anybody can win the reward. TellTheBell Survey visits https://tellthebell.ninja survey and Win $500 at taco bell feedback online.
Aftab Shaikh 18Aftab Shaikh 18
Thanks for sharing, this was actually useful. Would love to see more such interesting content. I build apps like gbwhatsapp (https://gbofficial.net/gbwhatsapp-apk-download/) and null's brawl (https://clashmod.net/nulls-brawl-download/), so I know how painful it is to face such issues. Anyways thanks for sharing!
Prashant allPrashant all
Super Blog! I would like to thank you for the efforts you have made in writing this post, will wait for your upcoming post
https://www.apksall.com/
https://www.apksall.com/toon-app-latest-apk/
Gochi SenGochi Sen
But many people like to play mobile game like https://relaxmodapk.com/brawl-stars-nulls/ and some of also want to play https://relaxmodapk.com/dream-league-soccer-2021-mod/ for free. So what do you think?
Nori KirisakiNori Kirisaki
Thank you all guys for sharing the solutions here.. (https://kinemastermods.com/kinemaster-mod-apk/).i appreciate all your help & efforts😀
Kevin Rhodes 15Kevin Rhodes 15
Thanks for sharing this valuable piece of information. Keep sharing more such awesome articles in the future. Also try FMWhatsapp (https://gbwamod.com/).
tyler lunartyler lunar
You must try the spotify++ (https://thetechbytes.net/spotify-plus-plus/) app and unblur course hero answers (https://thetechbytes.net/unblur-course-hero-answers/) on your smartphone. Just try these articles.
Kevin missKevin miss
Thank you sharing this informative post, and many people are play( https://megamodsapk.com/dream-league-soccer-2022/) smartphone and other android device. (https://megamodsapk.com/spotify-premium-mod-apk/)
tarry bradtarry brad
Encountering with similar issue, which is got solved by using GB instagram Apk at https://gbinstaa.com