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
Mazlow Cohen SFDCMazlow Cohen SFDC 

I want to use a for loop instead of a for each loop on a trigger....

Hi,

I was wondering how I could write a for loop instead of a for each loop to cycle through each object in the trigger. The reason being, I want to reference the number that object is in the List of objects in the trigger- later in the code after cycling through the loop. I have tried google searches and all the triggers seem to use this format- for each loop:

"for (User userInLoop : Trigger.new) {...}"

I tried using a for loop like this for account trigger- "for(Integer i = 0; i < Trigger.new.size(); i++) { 

Account a = Trigger.new.get(i);

//do some code on Account a...

}"


This kept giving me an error. Is this not allowed? 

Thanks!
Mazlow
Mazlow Cohen SFDCMazlow Cohen SFDC

I also tried this, which didn't work-

List<Account> Accs =  Trigger.new(); 

for(Integer i = 0; i < Accs.size(); i++) { 

Account a = Accs.get(i);

//do some code on Account a...

}
PavanKPavanK
Please try
 
list<Acccount> lstAccount = Trigger.new;
for(Integer i = 0; i < Trigger.new.size(); i++) 
{ 

Account a = lstAccount[i];


}

 
PavanKPavanK
list<Account> lstAccount = Trigger.new;
for(Integer i = 0; i < Trigger.new.size(); i++) 
{ 

Account a = lstAccount[i];


}
Correcting small typo error....
 
Mazlow Cohen SFDCMazlow Cohen SFDC
Thanks Pavan!! It worked!!!

Cheers!
Mazlow
PavanKPavanK
It will be helpfull if you can mark my answer/post as best.

Thanks