Sunday, September 9, 2018

Triggers in salesforce with example.

We use triggers to perform the operation before and after record changes.Before trigger are mainly used for validation purpose.After trigger are used for updating related records or for creating new records.



apex triggers

Following are the events on which trigger fires,


Triggers in salesforce examples


  1. Before insert
  2. Before update
  3. Before delete
  4. After insert
  5. After update
  6. After delete
  7. After undelete

Following are the Trigger context variable available,

trigger scenarios in salesforce


trigger.isbefore()

=>Check if the trigger is in before mode, If the trigger is in before mode it will return true.

trigger.isafter()

=>Check if the trigger is in after mode, If the trigger is in after mode it will return true.

trigger.isupdate()

Check if the trigger is in update mode, If the trigger is in update mode it will return true.

trigger.isdelete()

Check if the trigger is in delete mode, If the trigger is in delete mode it will return true.

trigger.isinsert()

Check if the trigger is in insert mode, If the trigger is in insert mode it will return true.

trigger.isundelete()

Check if the trigger is in undelete mode, If the trigger is in undelete mode it will return true.

trigger.isexecuting()

Check if the apex class method is getting called from apex trigger, If getting called return true.

trigger.new()

Stores new records.

trigger.newmap()

Stores new records with id's

trigger.old()

Stores old records.

trigger.oldmap()

Stores old records with id's.


Now,what is the difference between trigger.new,trigger.newmap,trigger.old,trigger.oldmap.

Trigger.new returns new records and Trigger.old return data before updates were done.

Trigger.newmap returns new records with id's and Trigger.oldmap return data before updates were done with id's.
                                                                                         
Sample trigger for contact name validation before insert, If contact first name is 'test' update it with 'test1'.

trigger contactnamevalidation on Contact(before insert)
{
for(contact obj:trigger.new)
{
if(obj.FirstName=='test')
{
obj.FirstName='test1';
}

}

}


TAGS:triggers in salesforce, apex triggers, Triggers in salesforce examples, trigger scenarios in salesforce.

No comments:

Post a Comment