Wednesday, 13 February 2013

Example for Bulk supported Trigger



  To write bulk safe triggers we need to understand and utilize sets and maps. Sets are used to isolate distinct records, while maps are name-value pairs that hold the query results retrievable by record id. for more details refer the Apex developer guide.

Example:
======

 trigger ChangeColor on Account (before insert, before update)
{
      // create a set of all the unique ownerIds
      Set<id> ownerIds = new Set<id>( );
      for (Account a : Trigger.new)
      {
           ownerIds.add(a.OwnerId);
      }
   
      // query for all the User records for the unique userIds
      Map<id, User> owners = new Map<id, User>([Select Favorite_Color__c from User Where Id in          
                                                      :ownerIds]);
     
      // iterate over the list of records being processed
      for (Account a : Trigger.new)
     {
           a.Owner_Favorite_Color__c = owners.get(a.OwnerId).Favorite_Color__c;
     }
}
Hi All,

    I have created this blog for who are willing to learn salesforce CRM and do developer certification
in salesforce.