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
I don't know. I just work hereI don't know. I just work here 

trigger while loop formula field Update

Any efficient way other than this?

 

trigger AutoAssignOpportunityNumber_AutoNoObj on Opportunity (before insert) {

   for (Opportunity o : Trigger.new)

 

{

       // Iterate over each sObject

        AutoNo__c au = [select NextNo__c, Iterator__c from AutoNo__c where Category__c = 'Opportunity Number' LIMIT 1 FOR UPDATE];

       if (o.Opportunity_Number__c == '' || o.Opportunity_Number__c == NULL)

        {

          while ([select count() from Opportunity where Opportunity_Number__c =:au.NextNo__c] > 0) {

                au.Iterator__c = au.Iterator__c + 1;

               // reflush the formula field

                update au;

                au = [select NextNo__c, Iterator__c from AutoNo__c where Category__c = 'Opportunity Number' LIMIT 1 FOR UPDATE];  <--- MUST RELOAD???

            }

            o.Opportunity_Number__c = au.NextNo__c;

            au.Iterator__c = au.Iterator__c + 1;

            update au;

        }

    }

}

Rahul SharmaRahul Sharma
Move the SOQL and queries out of the for loop. There is limitation on both of them and it is also not a good practice.