ONE DAY SALE

Free Salesforce Developers Tutorials >

Chapter - 9 Apex Triggers >

Types of Apex Triggers

Types of Apex Triggers

What You’ll Learn


S2 Labs

Types of Apex Triggers

1. Before Triggers

These are used to update/modify or validate records before they are saved to database.

2. After Triggers

These are used to access fields values that are set by the system like recordId, lastModifiedDate field. Also, we can make changes to other records in the after trigger but not on the record which initiated/triggered the execution of after trigger because the records that fire the after trigger are read-only.

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

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 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.

 

salesforce-developer

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *