SAVE UP to ₹4999/- OFF On All Salesforce Courses Claim Offer

9

Types of Apex Triggers in Salesforce

Apex Triggers in Salesforce are used to invoke various Apex code actions. They allow the user to perform custom actions before or after the new records or changed records saved to the database. It triggers on record cChanges such as insertions, updates, or deletions.

A trigger in Apex code can be executed before or after the following types of operations:

  • insert
  • update
  • delete
  • merge
  • upsert
  • undelete

Types of Triggers in Salesforce

There are two types of Triggers in Salesforce:

  1. Before Triggers: These triggers are used to update or validate triggering record values before they’re saved to the database.
  2. After Triggers: These are used to access fields values that are already set by the system like recordId, lastModifiedDate field for performing after save actions like sending mail. After Triggers are also used to make changes to other records. However, they cannot be used on the record which initiated/triggered the execution of after trigger because the records that fire the after trigger are read-only.

Apex Trigger Syntax

trigger TriggerName on ObjectName(trigger_events) {
    //code-block
 }

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.’);
}

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) {
    Contact contactRecord = new Contact(LastName = ‘Steve’);
    insert contactRecord
}
trigger ApexTrigger on Contact(after insert) {
    Account accountRecord = [SELECT Name FROM Account LIMIT 1];
    accountRecord.Name = ‘Updated Account’;
    MyException myExceptionObj= new MyException();
    throw myExceptionObj;
    // update accountRecord; // Not Allowed 
}

 

salesforce-developer

Trigger Events in Salesforce

Here is a list of trigger events in Salesforce.

Trigger Events in Salesforce
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Book A 15-Minutes Free Career Counselling Today!