Saturday, April 24, 2010

Bulk Triggers in Salesforce


Bulk Enabled 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 whcih can be inserted/updated/deleted through data loader or any other data migration tool.
I have explained writing a basic trigger here.


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 uploader 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 genaralised 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
       }
}



 
Hope this is useful.


Thanks
Srinivas,
www.trekbin.com

1 comment:

  1. thanx sir...its really useful
    Praful G.

    ReplyDelete