Apex Triggers in Salesforce

Apex Triggers in Salesforce

Apex Triggers in Salesforce

What is Apex Triggers in Salesforce?

Apex triggers enable you to perform custom actions before or after events to records in Salesforce, such as insertions, updates, or deletions. Just like database systems support triggers, Apex provides trigger support for managing records.

Use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface. For example, if validating a field value or updating a field on a record, use validation rules and workflow rules instead.

What is Trigger Syntax?

trigger TriggerName on ObjectName (trigger_events) {
   code_block
}

What are the various event on which a trigger can fire?

A trigger is a set of statement which can be executed on the following events. In above trigger events one or more of below events can be used with comma separated.

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

What are different type of Triggers?

There are two types of triggers:

  • Before triggers are used to perform a task before a record is inserted or updated or deleted. These are used to update or validate record values before they are saved to the database.
  • After triggers are used if we want to use the information set by Salesforce system and to make changes in the other records. are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field), and to affect changes in other records. The records that fire the after trigger are read-only.

What are the considerations while implementing the Triggers?

Consider the following before implementing the triggers.

  • Upsert trigger fires on 4 different events :- before(insert, update), after (insert, update)
  • Merge trigger are fired on both events on delete
  • Field history is updated after the trigger has successfully finished processing data.
  • Any callout should be asynchronous so that trigger does not have to wait for the response.
  • A trigger cannot have a static keyword in its code.
  • If a trigger completes successfully the changes are committed to the database and if it fails the transaction is rolled back.

Read the Apex Developer Guide for more detailed considerations.

What are context variables in triggers?

All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.

Following are the context variable available in triggers. Please note variable availability in trigger varies according to the type of trigger events.

  • isExecuting: Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
  • isInsert: Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
  • isUpdate: Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
  • isDelete: Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
  • isBefore: Returns true if this trigger was fired before any record was saved.
  • isAfter: Returns true if this trigger was fired after all records were saved.
  • isUndelete: Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
  • new: Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.
  • newMap: A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.
  • old : Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.
  • oldMap: A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.
  • size: The total number of records in a trigger invocation, both old and new.

Refer to Trigger context variables in salesforce link for more details.

Context Variable Considerations

Trigger EventCan change fields using trigger.newCan update original object using an update DML operationCan delete original object using a delete DML operation
before insertAllowed.Not applicable. The original object has not been created; nothing can reference it, so nothing can update it.Not applicable. The original object has not been created; nothing can reference it, so nothing can update it.
after insertNot allowed. A runtime error is thrown, as trigger.new is already saved.Allowed.Allowed, but unnecessary. The object is deleted immediately after being inserted.
before updateAllowed.Not allowed. A runtime error is thrown.Not allowed. A runtime error is thrown.
after updateNot allowed. A runtime error is thrown, as trigger.new is already saved. Allowed. Even though bad code could cause an infinite recursion doing this incorrectly, the error would be found by the governor limits.Allowed. The updates are saved before the object is deleted, so if the object is undeleted, the updates become visible.
before deleteNot allowed. A runtime error is thrown. trigger.new is not available in before delete triggers.Allowed. The updates are saved before the object is deleted, so if the object is undeleted, the updates become visible. Not allowed. A runtime error is thrown. The deletion is already in progress.
after deleteNot allowed. A runtime error is thrown. trigger.new is not available in after delete triggers.Not applicable. The object has already been deleted.Not applicable. The object has already been deleted.
after undeleteNot allowed. A runtime error is thrown.Allowed.Allowed, but unnecessary. The object is deleted immediately after being inserted.

Let’s see some examples of triggers in salesforce

Account trigger to set account rating as ‘Hot’ if account industry is ‘Banking’ or ‘Healthcare’

trigger AccountCustomTrigger on Account (before insert, before update) {
    for(Account acc : Trigger.New) {
	if(acc.Industry != null && (acc.Industry == 'Banking' || acc.Industry == 'Healthcare')){
	     acc.Rating = 'Hot';
        }
    }
}

Please note that in the above example we are not manually updating accounts using DML statement as it is before insert or before update trigger.

Let us see one more example of trigger on contact which will create Account record whenever contact is created without an account.

trigger ContactCustomTriggerExample on Account (after insert) {
    List<Account> accListToInsert = new List<Account>();
    for(Contact con : Trigger.New) {
        //check if account is null on contact
        if(con.AccountId == null ) {
            Account acc = new Account();
            //Add all required field on Account
            acc.Name = con.LastName;
            acc.Phone = con.Phone;
            accListToInsert.add(acc);
        }
    }
    if(!accListToInsert.isEmpty()){
	insert accListToInsert;
    }
}

Define Recursive Trigger and how to avoid it?

There is a possibility that the result of the trigger can end up calling the same trigger again and can run in a loop, this is known as a recursive trigger. To avoid this scenario we should create a static variable and check the value of this variable before we execute anything in the trigger. For more details refer to below link:

Avoid recursive trigger in salesforce

What do you mean by the bulkifying trigger?

A trigger should be able to handle single record and thousands of record. There are two important point for it:

  • Write triggers that operate on collections of sObjects.
  • Write triggers that perform efficient SOQL and DML operations.

If we will not follow above point we may hit governor limit when records are created/updated/deleted in mass using data loader or other tool.

Bulk Apex Trigger trailhead

For more detail about trigger in salesforce refer Official link

For interview questions related to salesforce refer to  Salesforce Interview Questions on Triggers

Permanent link to this article: http://www.sfdcpoint.com/salesforce/apex-trigger-in-salesforce/