Apex - Triggers


Advertisements

Apex triggers are like stored procedures which execute when a particular event occurs. A trigger executes before and after an event occurs on record.

Syntax

trigger triggerName on ObjectName (trigger_events) { Trigger_code_block }

Executing the Trigger

Following are the events on which we can fir the trigger −

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

Trigger Example 1

Suppose we received a business requirement that we need to create an Invoice Record when Customer's 'Customer Status' field changes to Active from Inactive. For this, we will create a trigger on APEX_Customer__c object by following these steps −

Step 1 − Go to sObject

Step 2 − Click on Customer

Step 3 − Click on 'New' button in the Trigger related list and add the trigger code as give below.

// Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
   List InvoiceList = new List();
   
   for (APEX_Customer__c objCustomer: Trigger.new) {
      
      if (objCustomer.APEX_Customer_Status__c == 'Active') {
         APEX_Invoice__c objInvoice = new APEX_Invoice__c();
         objInvoice.APEX_Status__c = 'Pending';
         InvoiceList.add(objInvoice);
      }
   }
   
   // DML to insert the Invoice List in SFDC
   insert InvoiceList;
}

Explanation

Trigger.new − This is the context variable which stores the records currently in the trigger context, either being inserted or updated. In this case, this variable has Customer object's records which have been updated.

There are other context variables which are available in the context – trigger.old, trigger.newMap, trigger.OldMap.

Trigger Example 2

The above trigger will execute when there is an update operation on the Customer records. Suppose, the invoice record needs to be inserted only when the Customer Status changes from Inactive to Active and not every time; for this, we can use another context variable trigger.oldMap which will store the key as record id and the value as old record values.

// Modified Trigger Code
trigger Customer_After_Insert on APEX_Customer__c (after update) {
   List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();
   
   for (APEX_Customer__c objCustomer: Trigger.new) {
      
      // condition to check the old value and new value
      if (objCustomer.APEX_Customer_Status__c == 'Active' &&
      
      trigger.oldMap.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {
         APEX_Invoice__c objInvoice = new APEX_Invoice__c();
         objInvoice.APEX_Status__c = 'Pending';
         InvoiceList.add(objInvoice);
      }
   }
   
   // DML to insert the Invoice List in SFDC
   insert InvoiceList;
}

Explanation

We have used the Trigger.oldMap variable which as explained earlier, is a context variable which stores the Id and old value of records which are being updated.

Advertisements