You need to sign in to do that
Don't have an account?
Trigger creating duplicate Case records
Hi,
I have a requirement to create a Case when the Oppportunity Stage is set to "Closed Won".
Below is the trigger that is doing this job. The problem is, its creating duplicates Case records when the Stage is set to "Closed Won".
Where Am i doing wrong?
Please advise.
trigger createNewCase on Opportunity (after update) {
List<Case> listcase = new List<Case>();
for(Opportunity o:trigger.new) {
Opportunity oldopp = trigger.OldMap.get(o.id);
if(o.StageName == 'Closed Won') {
//here APN_Related_Opportunity__c is lookup to Opportunity record for which new record is created
listCase.add(
new Case(APN_Related_Opportunity__c = o.id,
Subject = o.Name,
AccountId=o.AccountId,
Priority = 'Medium',
Status = 'New'));
}
}
if(listcase.size()>0) {
insert listcase;
}
}
Is it creating a duplicate everytime the first time the opportunity is set to Closed Won? Or do you mean it's creating extra cases for every subsequent edit of the opportunity afterwards?
If it's the former, the code seems like it will work for the initial update, if that's not the case could there be something else triggering an extra update on the opportunity object (aka workflow rule) which is causing the trigger to fire a second time?
Regardless you can probably just check on subsequent updates to make sure that the StageName is actually changing before the case is created:
This should cause the case to be created only if the case stage name was changed to closed won (the first time). Of course this won't work if the record was changed from Closed Won to something else, then changed back. If that's part of the requirements then you'll probably want to query on the case object to make sure there is no record with thats linked to that particular opportunity.
Hi Sean,
Sorry If I have confused you.
Scenario 1--When I create a new Oppty and directly save as "Closed Won", it creates a single Case. This is OK.
Scenario 2--
I create a new Opty and save it with Stage Name as (for e.g "New Proposal"). Then I edit and change the Stage Name as "Closed Won", which creates 2 Case records simultaneously.
Please let me know If I am not clear. Please advise.
Hmm the code you pasted is slightly off from the scenarios you're describing. The trigger code would only handle after updates so inserts wouldn't work. Do you have multiple triggers on the Opportunity object?
There are no other triggers at the moment in Oppty.
I am absolutely new to apex coding. If you could suggest the write code or modify my existing code I would be grateful.
My req is whenever the Opty stage is set to "Closed Won" it should create a new Case.
Try this: