Apex Triggers in Salesforce

Apex Triggers are special bundles of code that fire whenever an appropriate database action occurs. We can use Apex triggers to allow us to define complex logical processes that occur whenever a record is changed against the Salesforce database. Salesforce Apex triggers are executed based on record manipulation, results in the updation, insertion, or deletion of record or records. If any record is inserted, deleted, updated, we can write a trigger and do some work with the code.

Salesforce Apex Triggers syntax

Syntax of Trigger trigger trigger_name on object_name (events){
——-trigger body——-
}

These triggers are worked upon various events such as

  • Insert: This will run on Before and After condition.
  • Update: This will run on Before and After conditions.
  • Delete: This will run on Before condition only.
  • Upsert: This will run on Before and After only.
  • Undelete: This will run on After only.

A trigger can either run in a before context or an after context. The before and after here refer to the record being saved against the database, and in the case of a record being inserted, it receiving an Id. The combination of these contexts and types gives us a flexible framework with which we can create and manage repeatable changes and logic that we want to apply to our records as they enter and move throughout various states within the system. Again, it is worth reflecting on the fact that Salesforce is a transactional system, and as such triggers will be a primary focal point for a lot of our code-based development.

Before insert

Before insert triggers are the first triggers that can run on any record and do so before a record has been assigned an Id by being saved to the database. We should use before insert triggers to set any values on records we are inserting that are based on complex logic, or if we want to run any complex system validation. We want to set any values here as they will then be set on the record when it is inserted into the database, rather than requiring us to update the record again, stopping the record from having to undergo the same order of execution steps defined above.

For validation before insertion, it is best placed in a before insert trigger as if the record fails validation we can then error early and avoid having to roll back the record. Whilst rollback of the record is automatic, by failing the validation early we can ensure that we minimize the amount of work the system has to do and improve our solution’s speed.

After insert

After insert triggers run once the record has been saved to the database and been given an Id. At this point, we can query for the record from the database within our transaction context only. If the after insert trigger queries for a record using its Id, it will be retrieved, however, if any other transaction were to try and query for the record it would not be available until it is committed to the database at the end of the save order of execution.

We should use after insert triggers when we either require the Id, need to query for some other calculated field value or want to create or update additional records. We may require the Id when creating a series of default child records for example, or in passing the record Id to an asynchronous process. An example might be that on the insertion of a new account, we may make a call out to a web service that retrieves the account’s credit score. We would do this asynchronously, passing the account’s Id to the background process to retrieve the data it needed at runtime

Before update

A before update trigger runs before any changes made to an existing record are saved to the database. We should again use this before trigger for making any additional updates to values on the record or for custom validation logic. In this trigger, as we shall see later, we have access to both the old and new values on the record that enable us to compare the values and then make or validate changes as appropriate. For example, we may wish to validate that a record has changed from one status to another and not skipped an intermediary step. Again, we want to do this the before trigger fails early.

After update

An after update triggers fires once updates have been written to the database and should be used for either updating or creating related records, or when a value from the save is required, for example, a query to retrieve a formula field. A common use case for after update triggers is in calculating a total value for a parent record that is in a lookup relationship. For example, we may have a series of task records related to contact and wish to calculate the total number of open tasks related to each contact. For this, we would use an after update trigger to retrieve and count all the open tasks in the various states.

Before delete

The before delete trigger runs before a record is deleted from the database and should be used to validate that a record should be deleted and block that deletion otherwise.

After delete

Once a record deletion has been saved to the database but not committed, the after delete trigger runs. This trigger type should be used for cleaning up related records where a cascade delete will not occur, namely when the record being deleted is the parent in a lookup relationship that has not got the Don’t allow deletion of the lookup record that’s part of a lookup relationship option selected. Similarly, we may also use this trigger for updating related records like in our task total example in the after update trigger. If we deleted a task, we would want to update the related contact’s total.

After undelete

If a deleted record is retrieved from the recycle bin after it has been re-saved to the database the after undelete trigger will fire. This trigger allows us to recreate any relationships or set any values we wish on related records. Again, looking back to our example of tasks related to contacts, if a task was undeleted we would want to update the total number of tasks related to the contact record. We can see that triggers allow us to implement logic that manipulates and manages our record data throughout the entire record’s lifecycle. Within our triggers, we have access to special context variables that enable us to work with the data in various states as well as manage the flow of our triggers.

How to write a Trigger? 

There are multiple ways to write a trigger. Salesforce provides its development environment called developer console, similarly, we can use the VS code for writing a trigger. Writing Salesforce Apex Trigger using the developer console. Following are the steps: 

  •  Open your developer console
  • Go to File and then New
  • In the dropdown list, the second option is Apex Trigger, click on that.

Write the name of the trigger as Updatemobile and choose the sObject (Account )from the dropdown.