Salesforce Trigger Introduction And Trigger Real-time Scenarios






Introduction And Definition Of Trigger
  • The trigger is a Custom Apex Code, which will get fired automatically upon performing the DML Events.
  • By using Triggers, we can implement the complex validation rules, complex Business Logics, and Complex Transactional flows inside the application.
  • Triggers can fire on both "Before" and "After" performing the operations.
  • By using Triggers, we can perform all the DML operations(like insert, update, delete, upsert, undelete).
  • Triggers will get fired "Asynchronously".
  • Each trigger should be get associated with an object. But, an object can have one or more associated triggers. 


Syntax:

Trigger <TriggerName> ON <ObjectName>(<Events List>)
{
// Write the Business Logic.
}


Example:


Trigger AccountTrigger ON Account(<Events List>)
{
// Write the Business Logic..
}

Trigger RecruiterTrigger ON Custom_Object__c (<Events List>)
{
// Write the Business Logic..
}

Types of Triggers:

Apex Provides 2 types of Triggers as below.

1. Before Triggers:

These will get executes Before performing the operations on the records.
Ex: Before Insert, Before Update, Before Delete
Ex: Perform the Validations, Verify the Object Level Permissions, Updating the Rollup Summary values, Validation before Removing the Records, etc.

2. After Triggers:

These will get fired always After Performing the operations on the records 
After Insert, After Update, After Delete, After Undelete
Ex: Send the Email alerts, Execute the Assignment Rules, Update the Rollup Summary values, etc.

Trigger Events:

An Event is an Occasion / a Situation, which describes when the Trigger should get fired.
Each Trigger should be associated with One / More Events. We need to specify the Events by separating a Comma. (i.e. A Trigger can get fired on Multiple Events)

  • Before Insert.
  • Before Update.
  • Before Delete.
  • After Insert.
  • After Update.
  • After Delete.
  • After Undelete.
Example :

Trigger LeadTrigger1 ON Lead(Before Insert, After Insert)
{
// Writing the Validation Code..

// Write the Code to Copy the Lead Record into Prospect..
// Writing the code to Send Email Alert..
}

Trigger Context Variables:

Upon writing the Trigger code inside the Trigger, we need to segregate the code to be get fired based on the required events.

To segregate the required event's Code inside the trigger, we should aware of the Current Status of the Trigger.

We can get the current status of the trigger, by using "Trigger Context Variables" as below.

1. Boolean Trigger.isBefore:

It returns TRUE, if the Trigger is about to perform the operation. Else it returns FALSE.
2. Boolean Trigger.isAfter:

It returns TRUE, when the trigger is already done with the DML operation. Else it returns FALSE.
3. Boolean Trigger.isInsert:

It returns TRUE, when the trigger has been fire because of an insert operation. Else it returns FALSE.
4. Boolean Trigger.isUpdate:

It returns TRUE, when the trigger has been fired because of an Update operation. Else it returns FALSE.
5. Boolean Trigger.isDelete:

It returns TRUE, when the trigger has been fired because of a Delete operation. Else it returns FALSE.
6. Boolean Trigger.isUndelete:

It returns TRUE, when the trigger has been fired because of re-storing the records back to the actual object.
Ex:
Trigger LeadTrigger ON Lead(Before Insert, After Insert, before Delete)
{
If(Trigger.isInsert && Trigger.isBefore)
{
// Writing the Validation Code..
}
if(Trigger.isInsert && Trigger.isAfter)
{
// Write the Code to Copy the Lead Record into Prospect..
// Writing the code to Send Email Alert..
}
if(Trigger.isDelete && Trigger.isBefore)
{
// Write the Code..
}
}

7. Trigger.New:

It is a List Collection, which holds the current context records in the form of a "List Collection".
Syntax:

List<SObject> Trigger.New
  • Trigger.New Context variable will be available in both "Insert and Update" Operations.
  • Trigger.New Context Variable will not be accessible in "Delete" operation.
8. Trigger.Old:

It contains the Previous Context Records in the "List Collection" format.
Syntax:
List<SObject> Trigger.Old
  • Trigger.Old will be available only in "Update and Delete and Undelete" operations.
  • Trigger.Old will not accessible in "Insert" operation.
9. Trigger.NewMap:

It contains the Current Context records in "Map Collection" format.
Where
Key --> Record ID
Value --> Whole Record.
Syntax:
Map<Id,SObject> Trigger.NewMap
  • Trigger.NewMap will be accessible in "After Inser and in Update" operation.
  • Trigger.NewMap will not be available in "Before Inser and in Delete" operations.
10. Trigger.OldMap:

It contains the Previous Context records in "Map Collection" format.
Where
Key --> Record ID
Value --> Whole Record.
Syntax:
Map<Id,SObject> Trigger.OldMap
  • Trigger.OldMap will be accessible in "Update , Delete and Undelete" operations.
  • Trigger.OldMap will not be available in "Insert" operation.
Bulkification of Trigger:

As a Best Practice, always we have to make our trigger Bulkify. 
(i.e. Instead of firing the Trigger for each record operation separately, we need to make the Trigger should get fired only once for all the records).

i.e. The Trigger should be fired only once, and it should perform the operations on multiple records.

To achieve this, we need to hold all the records into a collection (Trigger Context Variables) and we need to iterate each record in the collection by using "FOR Loop" and perform the required operations on the records.

If all the records are validated successfully, then the records will get inserted into the object. Else it will abort the operation/transaction.

Ex:
Trigger LeadTrigger ON Lead(Before Insert)
{
// Holds the Newly inserting records into the Lead Object
// And iterate the collection to make the Trigger Bulkify.
for(Lead ld : Trigger.New)
{
// Write the Code to validate the Lead Record..
}
}

Trigger Real-time Scenarios Examples

1. Create a Trigger on Lead Object, which should validate the Lead Record, to make the "Lead Record's Email Id and Contact Number" mandatory.

Object Name: Lead
Event Name: Before Insert, Before Update


2. Create a Trigger on the Account object, To prevent the Deletion of an Active Account.

ObjectName : Account
Event Name : Before Delete


3. Create a Trigger, to Avoid the Duplicate Lead Records Based on the LastName and Email Id.

ObjectName : Lead Object
Events: Before Insert, Before Update


4. Whenever New Account Record is created then needs to create an associated Contact Record automatically.

Object Name: Account
Event name: After Insert



Trigger Best Practices:

  • The trigger should support bulk records as well - Always use "For Loop" to process records inside the trigger
  • Always check for null pointer exceptions.
  • Always use try and catch blocks in the trigger to handle Exceptions.
  • Differentiate events with separate blocks to avoid usage of trigger.new and trigger.old
  • Do not use DML operations inside the for loop. Add them to the list and update/insert/delete the list outside the for loop.
  • Do not use SOQL and SOSL statements inside for loop.
  • Write the Proper Test Classes for the Trigger. And maintain a minimum 1% of code coverage for each trigger. And Overall organization-wide, we have to maintain 75% of code coverage while moving the code from sandbox to production environment.
  • Avoid recursiveness in triggers by putting the proper conditions.

Post a Comment

Post a Comment (0)

Previous Post Next Post