Apex Trigger in Salesforce

What is an Apex trigger?

Trigger is piece of code that is executes before and after a record is Inserted/Updated/Deleted from the force.com database.
Syntax:
Trigger <trigger name> on <Object name> (trigger Events) {
// Implement the Logic here
}
Types of Triggers:
– Before Triggers
– After Triggers
Before Trigger: Before triggers are used to perform the logic on the same object and specifically we cannot use the DML operation (Insert, update, delete) on these triggers.
These triggers are fired before the data is saved into the database.
After Trigger: After triggers are used to perform the logic on the related objects and these triggers are used access the fields values that are created by system (Ex: CreatedBy, LasteModifiedBy , Record Id etc..).
Bulk Triggers:
By default every trigger is a bulk trigger which is used to process the multiple records at a time as a batch. For each batch of 200 records.
Trigger Context Variables:
All the trigger context variables are prefixed with “Trigger.” (Ex: Trigger.isInsert, etc..)
isInsert: Returns true if the trigger was fired due to insert operation.
isUpdate: Returns true if the trigger was fired due to update operation.
isDelete: Returns true if the trigger was fired due to delete operation.
isBefore: Returns true if the trigger was fired before record is saved.
isAfter: Returns true if the trigger was fired after record is saved.
New: Returns a list of new version of sObject records.
Old: Returns a list of old version of sObject records.
NewMap: Returns a map of new version of sObject records. (map is stored in the form of map<id,newRecords>)
OldMap: Returns a map of old version of sObject records. (map is stored in the form of map<id,oldRecords>)
Size: Returns a integer (total number of records invoked due to trigger invocation for the both old and new)
isExecuting: Returns true if the current apex code is a trigger.
The below table is tells what are the events we can use in the new trigger and old trigger
Trigger EventTrigger.NewTrigger.Old
Before InsertYesNo
Before UpdateYesYes
Before DeleteNoYes
Before UnDeleteNoYes
After InsertYesNo
After UpdateYesYes
After DeleteNoYes
Trigger Context Variable considerations:
– Trigger.Old is always readOnly
– We cannot delete trigger.new
– In before triggers, trigger.new can be used to update the fields on the same object.
– In After trigger, we get run time exception is thrown when user try to modify the fields in the same object.

Post a Comment

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget