How to bulkify trigger code

The term bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time. When a batch of records initiate Apex, a single instance of that Apex code is executed, but it needs to handle all of the records in that given batch.

Here is an example of poorly written code that only handles one record:

    trigger accountTestTrggr on Account (before insert, before update)  {
   
       //This only handles the first record in the Trigger.new collection
       //But if more than 1 Account initiated this trigger, those additional records
       //will not be processed
       Account acct = Trigger.new[0];
       List<Contact> contacts = [select id, salutation, firstname, lastname, email
                  from Contact where accountId = :acct.Id];       
    }


The issue is that only one Account record is handled because the code explicitly accesses only the first record in the Trigger.new collection by using the syntax Trigger.new[0]. Instead, the trigger should properly handle the entire collection of Accounts in the Trigger.new collection.

    trigger accountTestTrggr on Account (before insert, before update)  {     
       List<String> accountNames = new List<String>{};
     
       //Loop through all records in the Trigger.new collection
       for(Account a: Trigger.new){
          //Concatenate the Name and billingState into the Description field
          a.Description = a.Name + ':' + a.BillingState
       }       
    }


Notice how this revised version of the code iterates across the entire Trigger.new collection with a for loop. Now if this trigger is invoked with a single Account or up to 200 Accounts, all records will be properly processed.

Cheers!!!

1 comment:

  1. trigger OI_InsertCustomerId on Customer_Outstanding__c (before Insert,before update) {

    setaccids = new set();
    listlstacc = new List();
    list lstco = new List();



    lstacc=[select id,Customer_Code__c,Name from Account where Customer_Code__c!=null];

    for( Customer_Outstanding__c co : Trigger.new)
    {
    if(Trigger.isinsert)
    {
    for(Account acc : lstacc)
    {
    if(co.Customer_Code__c == acc.Customer_Code__c)
    {
    co.Customer__c = acc.id;
    }
    }
    }
    }
    for(Customer_Outstanding__c co : Trigger.new)
    {
    if(Trigger.isupdate)
    {
    for(Account acc: lstacc)
    {
    if(co.Customer__c != acc.id)
    {
    if(co.Customer_Code__c == acc.Customer_Code__c)
    {
    co.Customer__c = acc.id;
    }
    }
    }
    }
    }


    }


    this is my code to update account look up based on customer code in a custom object. How do i bulkify this code

    ReplyDelete