Here’s a quick example of how you can create a trigger in Salesforce Apex without a nested for loop:
Suppose you have a requirement where you want to update a field on Contact whenever an associated Account’s field is updated. You want to avoid nested for loops to avoid hitting governor limits.
Here’s how you can do it:
trigger AccountTrigger on Account (after update) {
Set<Id> accountIds = new Set<Id>();
for(Account acc : Trigger.new) {
accountIds.add(acc.Id);
}
List<Contact> contactsToUpdate = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds];
for(Contact con : contactsToUpdate) {
// update the field
con.SomeField__c = ‘New Value’;
}
update contactsToUpdate;
}
In this example, we used two separate for loops, not nested within each other. The first for loop is used to collect all the Account IDs from the accounts that were updated. The second for loop goes through the related contacts and updates a field.
This is a very basic example and your actual business logic might be more complex, but the principle remains the same: use collections like Lists or Sets to gather the data you need in one loop, then process that data in a separate loop. This is an efficient way to avoid nested for loops and stay within Salesforce’s governor limits.