Activity Forums Salesforce® Discussions Help for to create trigger but keep in mind( Avoid For loop inside for loop )

  • Help for to create trigger but keep in mind( Avoid For loop inside for loop )

    Posted by DINESH on May 16, 2023 at 4:59 pm

    Trigger for creating 10 contacts when an account record created.( Avoid For loop inside for loop )

    Shuvam replied 1 year, 6 months ago 2 Members · 1 Reply
  • 1 Reply
  • Shuvam

    Member
    May 17, 2023 at 2:31 pm

    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.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos