What is Trigger?

Trigger is an Apex Code that executes before or after changes occurs to Salesforce records.

These changes includes operations like Insert, Update, Delete, Merge, Upsert and Undelete.

When to Use Triggers

  1. An Apex Trigger is a Stored Apex procedure that is called whenever a record is inserted, updated, deleted, or undeleted. If any change happens to a single or multiple records, the Apex Trigger created on that object will be fired. 
  1. For example, we can have a trigger run:
    • Before an object’s record is inserted into the database.
    • After a record has been deleted.
    • Even after a record is restored back from recycle bin.
  2. Use triggers to perform tasks that can’t be done using a point & click tool in Salesforce. If the task is possible using point & click tools then always prefer doing it from them.
  3. Triggers are active by-default when created and Salesforce automatically fires active triggers when specified database event occurs.

Types of Apex Triggers

  • Before Triggers
  • After Triggers

Syntax & Trigger Events:

trigger TriggerName on ObjectName (trigger_events)

{

//code-block

}

where trigger-events can be a comma-separated list of one or more of the following events:

  • Before insert
  • Before update
  • Before delete
  • After insert
  • After update
  • After delete
  • After undelete

Example:

Trigger firstTrigger on Account(before insert)

{

System.debug(‘I am before insert.’);

}

Trigger secondTrigger on Account(after insert)

{

System.debug(‘I am after insert.’);

}

For example:

Update Account a;

(Before update Trigger of Account a)

{

Inserts contact b;

}

(after insert of contact B)

{

Insert a; // over here we are updating Account a in its before trigger

// indirectly i.e. not allowed.

}

Note: If you update or delete a record in its before trigger, or delete a record in its after trigger you’ll receive an error and this includes both direct and indirect operations.

trigger ApexTrigger on Account (before update) 

{

    //See trigger3

    Contact c = new Contact(LastName = ‘Steve’);

    insert c;

}

trigger ApexTrigger on Contact (after insert) 

{

    Account a = [Select Name from Account Limit 1];

    a.name = ‘Updated Account’;

    MyException me = new MyException();

    throw me;

    //update a; // Not Allowed

}

Triggers can modify other records of the same type as the records that initially fired the trigger.

As triggers can cause other records to change and because these changes can, in turn, fire more triggers, the apex runtime engine considers all such operations a single unit of work & sets limits on the number of operations that can be performed to prevent infinite recursion.

Our Recent Blog

Share This Post