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
nitr0gennitr0gen 

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:
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?
SfdcStevenSfdcSteven
You want to do that in a before trigger (or a workflow field update). What's happening is that the "update c" call is causing it to infinitely recurse. You also don't need to perform the query

trigger closedWonTrigger on Opportunity bulk (before update) {
for (Opportunity o : Trigger.new) {
if (o.StageName == 'Closed Won') {
o.Closed_Won__c = true;
}
}
}
nitr0gennitr0gen

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:

trigger closedWonTrigger on Opportunity bulk (before update) {
 for (Opportunity o : Trigger.new) {
  if (o.StageName == 'Closed Won' && o.Closed_Won__c = false) {
   o.Closed_Won__c = true;
  }
 }
}