Friday, May 3, 2013

Bulk Triggers in Salesforce

When you have a need of writing a trigger, it is strongly recommended that you make it bulk enabled, so that the trigger can handle number of records which can be inserted/updated/deleted through data loader or any other data loader.

I will explain how to bulk enable a trigger now in this article. Consider a scenario where you might want to update the opportunity status to "Closed-Won" depending on a Boolean field CloseOpportunities__c on each of the account that has been updated (That is, if you want to close the opportunities related to accounts that are being updated). And you will be uploading hundreds of accounts using a data loader tool.

Here is the trigger.
 Trigger myTrigger on Account(after update)   
 {   
   Set <Id> setAccId = new Set<Id>();   
   for(Account a: Trigger.new)   
   {   
     if(a.CloseOpportunities__c)   
       setAccId.add(a.Id);//set always contains distinct Ids   
   }   
   list <Opportunity> lstOpp = [select Id, StageName from Opportunity where AccountId in : setAccId];   
   for(Integer i = 0; i < lstOpp.size(); i++)   
   {   
     lstOpp[i].StageName = "Closed-Won";   
   }   
   if(lstOpp.size() > 0)   
     update lstOpp;   
 }   

And a more generalized way is something like this

 tirgger MyTrigger on SObject([your events goes here comma seperated])   
 {   
     Set<Id> SetOfIds = new Set<Id>();   
     for(SObject s : trigger.new)   
     {   
        SetOfIds.add(s.idField);   
     }   
     Map<Id,SObject> objMap = new Map<Id,SObject>([select Id, [Other Fields] from SObject where Id in : SetOfIds]);   
     for(SObject s : trigger.new)   
     {   
        //do your processing with map   
     }   
 }  



No comments: