You need to sign in to do that
Don't have an account?

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());
}
}
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());
}
}
Try this and Let me know the results,
Thanks & Best Regards,
Vignesh.B
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