Search Here

How do you handle bulk operations in Salesforce Triggers?

 In my experience, handling bulk operations in Salesforce triggers is essential to ensure that your trigger can efficiently process large volumes of records without hitting Salesforce’s governor limits. The key technique for managing bulk operations is bulkification, which involves writing trigger code that processes multiple records in a single transaction rather than handling each record individually.

trigger AccountTrigger on Account (before update) {

    Set<Id> accountIds = new Set<Id>();

    

    // Collect the IDs of all accounts being updated

    for (Account acc : Trigger.new) {

        accountIds.add(acc.Id);

    }

    

    // Query related contacts in bulk

    List<Contact> contactsToUpdate = [SELECT Id, Email FROM Contact WHERE AccountId IN :accountIds];

    

    // Perform bulk operations on the queried contacts

    for (Contact con : contactsToUpdate) {

        con.Email = 'updated@example.com'; // Example logic

    }

    

    // Perform a bulk DML update

    if (!contactsToUpdate.isEmpty()) {

        update contactsToUpdate;

    }

}

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.