You need to sign in to do that
Don't have an account?
nitr0gen
Update existing opportunity with APEX
I need to be able to set a flag when an opportunity is saved... The flag will remain false until the opportunity stage is "Closed Won". Although I can implement this using workflow, changing business processes have made the task a bit more challenging and I will need the added functionality of APEX.
This is what I have so far:
Code:
This compiles without errors, but I get runtime errors of:
trigger closedWonTrigger on Opportunity bulk (after update) { Opportunity c = [select StageName from Opportunity]; if (c.StageName == 'Closed Won') { c.Closed_Won__c = true; update c; } }
This compiles without errors, but I get runtime errors of:
"maximum trigger depth exceeded Opportunity trigger event" or "System.QueryException: Array has more than 1 row for assignment to SObject"
I'm fairly new to APEX, but something about working with AJAX in the past tells me I'm missing the opportunity id somewhere?
trigger closedWonTrigger on Opportunity bulk (before update) {
for (Opportunity o : Trigger.new) {
if (o.StageName == 'Closed Won') {
o.Closed_Won__c = true;
}
}
}
Thanks, that did the trick!
For some reason I thought that the fields I needed wouldn't be accurately detected in the "before update" trigger, which is why I was using "after update".
In any case, I wanted to set up an email alert once the opportunity became "Closed Won". This can easily be done through a Workflow Email Alert. However, opportunities in my case can be changed back and forth between Closed Won / Needs Analysis/ Proposal/ etc. I only wanted to send an alert the *first* time the opportunity became Closed Won, and not every time thereafter.
I tried setting up two workflow rules: one workflow field update to set a flag, and a workflow email alert based on that flag. Unfortunately, I found that one workflow rule cannot trigger another.
With this Apex trigger, the process works flawlessly! :smileyvery-happy:
Code: