+ Start a Discussion
Fares AlsyoufiFares Alsyoufi 

Beginner question - Why do we run this loop in almost every trigger?


I'm new to Apex programming and I noticed this trend in building Apex triggers. Almost every trigger I saw include this code: 
//Create a set that includes all the account ids
Set<Id> AccIds=new set<Id>();
/*Go through a list of accounts and assign Ids (generated in the set) to all account rows in the list*\
    for(Account a:trigger.new)
//Also why do you always use trigger.new method?

A detailed explanation would be highly appericiated?

Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello Fares,

Trigger.new is a context variable.

To access the records that caused the trigger to fire, use context variables. For example, Trigger.New contains all the records that were inserted in insert or update triggers. Trigger.Old provides the old version of sObjects before they were updated in update triggers, or a list of deleted sObjects in delete triggers. Triggers can fire when one record is inserted, or when many records are inserted in bulk via the API or Apex. Therefore, context variables, such as Trigger.New, can contain only one record or multiple records. You can iterate over Trigger.New to get each individual sObject.

In your example this code would be in a trigger for the Account sObject. As context variables are dependent of the context, its values can have different types of sObject. Let's say that you creates a trigger for the Contact sObject, then the code would be something like:
for (Contact con : Trigger.new) {
     // do something

I strongly recommend you this reading:

If you have knowledge in other programming language such as C# or Java, you might find this helpful as well:
https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices (http://​https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices)

Hope to have helped!


Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
Fares AlsyoufiFares Alsyoufi
Hi Zuinglio,

Thanks for your quick and elaborative response. One peice I'm still not getting though. Why are we creating the Set <ID> of accounts ids and assinging them to the a records in list (line 2 and 6)? 

Thanks again,