Tuesday, December 18, 2012

Apex Trigger in Force.com

Apex Trigger in Force.com platform is a procedure written in Apex programming language that operates on an object at the defined events. The events could be before or after records are inserted, updated, or deleted in the database.

When the trigger is running, there could be several records meeting the criteria. For example, you have a trigger defined on object Account, at event before inserting. When the trigger is running there could be many Account records that are being inserted. Your trigger procedure runs on all these Accounts. As you can see since the trigger is fired when database records are manipulated, your trigger code is probably further manipulating the data that is being stored.

System.Trigger class provides all the information related to the trigger that is being fired. Within the Trigger procedure, using the instance of this class you can figure out the operation that triggered the event. Using the same System.Trigger class, you can also have access to the new data if insert/update trigger as well as the old data prior to the operation if it is update/delete trigger.

Triggers are defined on the objects. On object definition detail page, there is a section called Triggers. This is where you can add/manage triggers. Trigger code is compiled when it is saved and must compile successfully to be able to save.

Apex Trigger procedure syntax is -

trigger TriggerName on ObjectName (events) {

code_block

}

where events can be comma separated list of one or more of the following -
  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete
Any database changes made by trigger are automatically committed on successful completion of the trigger, otherwise changes are rolled back.

That is in brief about the Apex Trigger. You can understand the workings of this better by implementing some of the triggers.

Happy cloud computing using Salesforce!

No comments:

Post a Comment