Wednesday, July 9, 2014

How to write basic trigger with bulk handling

So in Salesforce.com one of the basic things is to write trigger on objects to automate the functional flow according to the business logic. And many of us face the problem in the starting to how to get started with triggers in salesforce. The basic syntex is given below

<sObject Name>   = write the name without the angular parenthesis
<trigger events> = write events as before insert, before update, after insert, after update, before delete, after undelete
trigger on <sObject Name> <trigger Name> (<trigger events>) {
 //Logic for trigger events
}
Now to write it for single record.

trigger on Account tAccountBIBU (before insert, before update) {
 //Check for events
 if(trigger.isBefore && trigger.isInsert){
  trigger.new[0].Description = 'Hi This is test Insert'; 
 }
 if(trigger.isBefore && trigger.isUpdate){
  trigger.new[0].Description = 'Hi This is test Update'; 
 }
}
The above code is not bulkefied as it will only effect the [0] element in the list.
trigger on Account tAccountBIBU (before insert, before update) {
 //Check for events
 if(trigger.isBefore && trigger.isInsert){
  for(Account acc : trigger.new){
   acc.Description = 'Hi This is test Insert'; 
  }
 }
 if(trigger.isBefore && trigger.isUpdate){
  for(Account acc : trigger.new){
   acc.Description = 'Hi This is test Update'; 
  }
 }
}
Now the above code is bulkefied and will effect every record in the trigger.new list

Hope this helped you!!

No comments:

Post a Comment