Hello folks, In this tutorial I am going to describe apex trigger, It’s type and syntax for writing a trigger in Salesforce.

After completing this tutorial you’ll be able to:
  • Write a trigger for a Salesforce object.
  • Use trigger context variables.
  • Call an apex class method from a trigger.

So let’s begin,

What is apex trigger?

Apex trigger is the piece of apex script that executes before or after specific DML (Data manipulation language) events occur, such as before Salesforce object records are inserted or updated or deleted. You can use specific conditions in triggers to perform operations also you can use triggers to do anything that you want to do in apex like executing SOQL and DML or calling Apex methods.

A trigger executed before or after the following types of operations:
  • Insert
  • Update
  • Delete
  • Merge
  • Upsert
  • Undelete

Trigger syntax

A trigger definition starts with the trigger keyword. Then followed by the name of the trigger, the Salesforce object that the trigger is associated with, and the events under it fire. A trigger has the following syntax:
 trigger TriggerName on ObjectName (trigger_events) {
   //codeblock
 }
Example:
 trigger HelloWorldTrigger on Account (before insert) {
     System.debug('Hello World!');
 }

Types of triggers

There are two types of triggers.

Before triggers: Before triggers are used to update or validate records before they’re saved to the Salesforce objects.

After trigger: After triggers are used to access field values set by the system like record’s Id or LastModifiedDate. And also use to affect changes on other records. After triggers are fired on which records those are read-only.

Types of context variables

There are two context variable in a trigger,

Trigger.New: Contains all the records that were inserted in insert or update triggers.

Trigger.Old: Provide the old version of sObjects before they were updates in update triggers or a list of deleted sObjects in a deleted trigger.

Example:
 trigger HelloWorldTrigger on Account (before insert) {
    for(Account a : Trigger.New) {
        a.Description = 'New description';
    }
 }
Calling an apex class method from a trigger

You can call apex class methods from a trigger. Calling methods from classes enables code reuse and also reduce the size of a trigger.

Example:

The following example shows how to call a static method from a trigger.
 public class MyClass{    
    public static void myMethod(Account a){        
        // code block        
    }    
 }

 trigger CallingClass on Account (after insert) {    
    for(Account a : Trigger.New) {        
        MyClass.myMetho(a);        
    }     
 }

See also:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.