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
chithra srinivasanchithra srinivasan 

closed opportunity trigger System.QueryException: List has more than 1 row for assignment to SObject

Hi,
   I am trying out the Closed Opportunity Trigger Challenge in Bulk  Apex Trigger Trailhead. I am getting the error : " System.QueryException: List has more than 1 row for assignment to SObject" when I perfomed the Execute Anonymous. Eventhough I could make the code more efficient, would like to know the cause of the error. Any help is appreciated and here is the code:

trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    try {
         List<Opportunity> Opps = [SELECT Id,StageName FROM Opportunity
          WHERE Id IN :Trigger.New];
       
   List<Task> tasks = new List<Task>();

    Task t = new Task();
        for(integer i=0; i<Opps.size(); i++) {
          if(Trigger.isInsert || Trigger.isUpdate) {
            if (Opps[i].StageName == 'Closed Won'){

                t.Subject = 'Follow Up Test Task';
                t.WhatId = Opps[i].Id;
                tasks.add(t);
                                
            }
          }   
        }
    System.debug(tasks.size() + '  tasks size');
     if(tasks.size() > 0) {  
      insert tasks;
     }    
    }catch (DmlException e) {
        System.debug('A DML exception has occurred: ' +
                    e.getMessage());
    } 
   
}
VIGNESH BALASUBRAMANIANVIGNESH BALASUBRAMANIAN
Hi Chithra,

Try this and Let me know the results,
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {
    try {
	
	Id i;
	for(Opportunity op : trigger.new)
	{
		i=op.Id;
	}
         List<Opportunity> Opps = [SELECT Id,StageName FROM Opportunity WHERE Id =:i];
        for(integer i=0; i<Opps.size(); i++) {
                if (Opps[i].StageName == 'Closed Won'){
				Task t = new Task();
                t.Subject = 'Follow Up Test Task';
                t.WhatId = Opps[i].Id;
				t.OwnerId = Opps[i].OwnerId;
                insert t;                  
            }        
        }
    System.debug(tasks.size() + '  tasks size');
     if(tasks.size() > 0) {  
      insert tasks;
     }    
    }catch (DmlException e) {
        System.debug('A DML exception has occurred: ' +
                    e.getMessage());
    }  
}

Thanks & Best Regards,
Vignesh.B
chithra srinivasanchithra srinivasan
Hi Vignesh,
     Thanks for replying. But even after I changed your code and also by changing the integer variable i to j and removing tasks list, still getting the same error. The cause of the error is still unknown.
Thanks,
Chithra