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
GailGail 

Opportunity before update - trigger.new issue

I have a before update trigger on Opportunity where I am avoiding a SOQL for loop using the example at https://developer.salesforce.com/page/Best_Practice:_Avoid_SOQL_Queries_Inside_FOR_Loops. Before I did this and used for(Opportunity o: trigger.new), the code worked fine (except, of course, on my load tests, which caused me to change this).

List<Opportunity> oppsWithOLIs = [select id, IsWon, Assets_Created__c,(select id from OpportunityLineItems where
                                  (product2.family = 'Subscription'or product2.family = 'Support'))
                                   from Opportunity  where Id in :Trigger.newMap.keySet()];

The problem is, my IsWon is returning as false when I'm changing the stage to a Won stage and returning as true when I'm change from a Won stage to an Open stage. I've tried using stagenames too and it keeps returning the old value. With Trigger.newMap, shouldn't it be returning the newly set value?

The other issue I'm running into is that in the for loop (for Opportunity o: oppsWithOLIs), I'm trying to set the opp value Assets_Created__c to true and this is not happening. However, the rest of the code where I do a for loop on the OLIs, add to a list and then outside of a loop add those to an apex class is running fine.  
Best Answer chosen by Gail
SeAlVaSeAlVa
Hi, 

there is an easy explanation.

You are quering the database for Opportunities you have just updated on a BEFORE UPDATE trigger, what means that all the information you retrieve from your query will be as it was before updating.

Two of the options you have are:
  • Change to an AFTER UPDATE trigger
  • Get the flag from your trigger.newMap (trigger.newMap.get('IdOfTheRecordYouAreTryingToReadTheInformationFrom').isWon

Kind Regards

If it helps, please mark it as "Best Answer", otherwise reply with your doubts.

All Answers

SeAlVaSeAlVa
Hi, 

there is an easy explanation.

You are quering the database for Opportunities you have just updated on a BEFORE UPDATE trigger, what means that all the information you retrieve from your query will be as it was before updating.

Two of the options you have are:
  • Change to an AFTER UPDATE trigger
  • Get the flag from your trigger.newMap (trigger.newMap.get('IdOfTheRecordYouAreTryingToReadTheInformationFrom').isWon

Kind Regards

If it helps, please mark it as "Best Answer", otherwise reply with your doubts.
This was selected as the best answer
GailGail
Thanks! I did end up changing it to an after update but the info on how to find the new value is great - I obviously did not know that :S