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
Narasimha LakshmiNarasimha Lakshmi 

Getting this error when writing the following trigger,May i know where i did mistake.....

trigger ClosedOpportunityTrigger on Opportunity (before insert,before update) {
    List<task> tsklst=new List<task>();
   List<Opportunity> opplst=new List<Opportunity>([select id,StageName from opportunity where id in:Trigger.New]);
    //List<Opportunity> opplst=new List<Opportunity>();
    if(Trigger.isInsert || Trigger.isUpdate)
    {
       if(opplst.StageName =='Closed Won')
        {
            for(Opportunity opp:Trigger.new){
                
                system.debug('@@@@@@@' +opp);
         Task t=New Task();
             t.WhatId = opp.id;
            t.Subject = 'Follow Up Test Task';
            tsklst.add(t);
            } 
        }
        insert tsklst;
        
    }
}
ZhanLevovZhanLevov

Hi Narasimha,

I did not quite get your error from your post, but my guess is that your list of Opportunities is empty.

Also your logic is messed up.

Problems with your code:

List<Opportunity> opplst=new List<Opportunity>([select id,StageName from opportunity where id in:Trigger.New]);

To get the Opportunities with the IDs of the records that entered the Trigger, you would have to pass the IDs of those records.

Trigger.New will return List<Opportunities> and  ''WHERE ID IN : Trigger.New" would not make any sense. It would expect IDs and you are passing records. To make this work you would have to pass the IDs of those records.

List<Opportunity> opplst=new List<Opportunity>();
opplst = [SELECT id,StageName FROM opportunity WHERE id IN : Trigger.newMap.keySet()];

After that you are trying to access StageName of a record, but passing the List.

if(opplst.StageName =='Closed Won')


Here either you must specify which record you want to get, the first would be:

if(opplst[0].StageName =='Closed Won')

Then you would iterate through the Trigger New.

This is problem with the code, however there is problems with your logic.

The main is, why would you query the records that are inside the trigger, when you have them in Trigger.New?

The code would probably look something like this:

List<Opportunity> oppLst = Trigger.New; //this is the list with all the records.
List<Task> tsklst = new List<Task>();   //the list with the tasks that will be inserted

if(Trigger.isInsert || Trigger.isUpdate){

    for(Opportunity currentOpp : oppLst){

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

            Task t=New Task();
            t.WhatId = opp.id;
            t.Subject = 'Follow Up Test Task';
            tsklst.add(t);
        } 
    }

    if(!tsklst.isEmpty()){
        insert tsklst;
    }
}