Automate Processes Using Apex Triggers in Salesforce [Detailed Guide]

As a Salesforce Developer, I was assigned the task of automating the process of assigning high-priority cases (e.g., “Critical” or “High”) to a specialized support team.

This should happen when a case is created or its priority is changed. To fulfill this requirement, I need to develop an Apex trigger program.

In this tutorial, I will explain how to automate processes using Apex Triggers in Salesforce, when to create triggers, and how to declare and implement them.

What are Apex Triggers in Salesforce?

Triggers in Salesforce Apex are code that is automatically executed before or after certain Salesforce DML events occur.

They perform actions such as updating related records, enforcing custom business logic, or automating processes when data changes in Salesforce.

For example, you can run a trigger before an object’s records are inserted into the database, after deleted records, or even after a record is restored from the Recycle Bin.

When do we use Apex Triggers in Salesforce Apex?

If any change happens to single or multiple records, the Apex Trigger created on that object will be fired. For example, we can have a trigger run:

  • Before an object’s record is inserted into the database.
  • After a record has been deleted.
  • Even after a record is restored from the recycle bin.

Triggers can be used to perform tasks that can’t be done using a point-and-click tool or flow in Salesforce. If the task can be done with flows, it is best to do so.

Trigger events in Salesforce Apex

The trigger responds to DML (data manipulation language) events on Salesforce objects, such as insert, update, and delete.

There are the following two types of triggers in Salesforce Apex:

  • Before: These triggers execute before data is saved to a Salesforce database, called a before trigger.
    • Data Validation.
    • Calculation.
    • Precommit Action.
  • After: It is executed after data is saved to the Salesforce database.
    • Alerts.
    • Submission.
    • Automation Action.
    • Post-commit Action.

Below, I have shown how to use trigger type with the events to automate any process. For that, we need to write like Trigger Type + Event (DML Operation).

Before InsertAfter Insert
Before UpdateAfter Update
Before DeleteAfter Delete
After Undelete

Apex Trigger Syntax

trigger TriggerName on ObjectName (trigger_events) {
    //enter your code;
 }

Automate Processes Using Apex Triggers in Salesforce

Below, I will explain how we can automate the processes using an Apex trigger in Salesforce to make the task easier.

In the Apex trigger code below, I have explained how to automatically create a related contact record with the account name when an account record is created.

To create the Apex trigger, click the File -> New -> Click the Apex Trigger.

Create Apex Trigger in Salesforce

Then, enter the Name of your trigger, select the Object on which you want to create the trigger from the drop-down menu of sObject, and click the Submit button.

How to Create Apex Trigger in Salesforce

Then you will see the trigger will be created as per the name and sObject you provided. With that, you will also see a default trigger event displayed. You can change the trigger event as needed.

automate processes using Apex Triggers in Salesforce

Now, we need to change the default event so we can create a related record for the account.

When we need to create, update, or perform any other action with another object, we need to use the after event, so I entered it ‘after insert‘ the event.

Then, I created a list to store the contact record, which will be created after the account record. In loop, we created an account instance with the Trigger.new context variable containing a list of new versions of the records.

After that, assign account fields to the contact object’s fields, add contacts to the list, and then, outside of the for loop, perform a DML operation to insert the contact list into the Salesforce database.

trigger TriggerDemo on Account (after insert) {
    
    List<Contact> con = new List<Contact>();
    
    for (Account acc : Trigger.new) {
        Contact c = new Contact ();
        c.FirstName = 'Account of';
        c.LastName = acc.Name;
        c.AccountId = acc.Id;
        
        con.add (c);
      }        
    insert con;
}

Now, navigate to the Apex Triggers from setup, search for Apex trigger in the Quick Find box, and there you will see the trigger Status.

If the status is Active, then it will work. Otherwise, the trigger will not automatically create a contact.

Apex Trigger in Salesforce

Now, I’m creating the account record with the name shown in the image below and saving it.

After that, open the Contact object tab, and you will see that the contact associated with the account record is automatically created.

Use Salesforce Apex Triggers

The contact has been successfully created with the name you entered in the account record and the ‘Account of‘ prefix we entered in the Apex trigger code.

Activate Triggers in Salesforce

In this way, we can create an Apex trigger in Salesforce to automate any process. Then we have a trigger context variable that is used to manipulate records.

Trigger Context Variable in Salesforce Apex

Trigger context variables in Salesforce Apex provide information about the records that fired the trigger and the context in which the trigger was executed.

These variables allow developers to access inserted, updated, deleted, or undeleted records and perform actions based on that context.

Types of context variables in the Salesforce trigger:

  1. Trigger.size: The total number of records in a trigger invocation.
  2. Trigger.isInsert: Returns true if the trigger is fired due to an insert operation.
  3. Trigger.isUpdate: Returns true if the trigger is fired due to an update operation.
  4. Trigger.isDelete: Returns true if the trigger is fired due to a delete operation.
  5. Trigger.isBefore: Returns true if the trigger is fired before the record is saved.
  6. Trigger.isAfter: Returns true if the trigger is fired after the record is saved.
  7. Trigger.new: Returns a list of the new versions of the sObject records.
  8. Trigger.old: Returns a list of the old versions of the sObject records.
  9. Trigger.newMap: A map of IDs to the new versions of the sObject records.
  10. Trigger.oldMap: A map of IDs to the old versions of the sObject records.

1. Trigger.new Context Variables in Apex Trigger

The Trigger.new context variable contains a list of new versions of the records that are being inserted or updated. It’s available ‘before insert and update’, and ‘after insert and update’ triggers.

For example, whenever I create an account record, the other fields where I want to set default values should get automatically saved. In the code below, I will explain how we can do that.

Here, I’m using the before insert trigger event because we are creating a record for the same object.

Then, in each loop, we declare Trigger.new, which returns the list of records on which we are trying to perform a DML operation.

In the for loop, I assigned values to the account fields so that when we create the account record and don’t fill these fields, the values we assigned will be automatically added to the record.

trigger AccountTrigger on Account (before insert) {
       for (Account acc: Trigger.new) {
           acc.Active__c = 'Active';
           acc.Rating = 'Hot';
      }
}

Here, you can see I only filled out the account name field and saved the record directly.

Trigger.new in Salesforce Apex

As you save the record and open the account details, you can see the values we assigned in the Apex trigger displayed there.

Trigger Context Variable in Salesforce Apex

2. Trigger.old Context Variables in Apex Trigger

In Salesforce, Trigger.old holds the previous versions of records that are being updated or deleted. This is useful when you want to compare old and new values during a trigger operation.

You can access Trigger.old in the following trigger events: before update, after update, before delete, and after delete.

For example, if you set the account status, you don’t want any other user to change it. Even if it is editable, you can use trigger.old to fetch the existing account status and check with the new status. If it does not match, prevent the record from being saved.

trigger TriggerDemo on Account(before insert) {
    
   for ( Account oldAcc: Trigger.old ) {
        for ( Account newAcc: Trigger.new ) {
            if ( oldAcc.Id == newAcc.Id && oldAcc.Active__c != newAcc.Active__c ) {
                newAcc.Active__c.addError( 'Amount cannot be changed' );
            }
        }
    } 
}

3. Trigger.newMap Context Variables in Apex Trigger

In Salesforce triggers, the Trigger.newMap is a map of record IDs to the new versions of the records. It is available in before insert, before update, after insert, and after update triggers.

This map allows us to easily access records by their IDs, making it useful when you need to retrieve a specific record based on its unique identifier.

For example, we want to update the mailing city of the contact records whenever we update the billing city related to the account records.

In the Apex trigger code below, I created a trigger on the account object and used the after update event because we are updating the related object’s record.

Then I created a map with ID as the key and sObject Account as the value, and assigned it to newMap.

After that, I created a list and fetched contacts using the KeySet to get them from the contact object associated with the account in Trigger.newMap.

Then, I added a loop for each contact and passed the list of contacts that we fetched to the contact object instance.

After that, create an account sObject to store the account record associated with the contact, assign the account billing city to the contact’s mailing city, and then simply update the contact list.

trigger TriggerDemo on Account(after update) {
        
    Map<Id,Account> nMap = new Map<Id,Account>();
    nMap = Trigger.newMap;
    List<Contact> cList = [ SELECT LastName, AccountId FROM Contact WHERE AccountId IN: nMap.keySet() ];
    
    for (Contact c : cList) {
        Account a = nMap.get(c.AccountId);
        c.MailingCity= a.BillingCity;
    }
    update cList;
}

Now navigate to the account records with an associated contact, update the billing city, and save the record.

Trigger.newMap &amp; Trigger.oldMap Context Variable in Apex Trigger

Here, you can see in the first image that the mailing address is null. As you update the billing address in the account, you will see that address in the mailing address.

Create Trigger in Salesforce Apex

4. Trigger.oldMap Context Variables in Apex Trigger

The Trigger.oldMap is a map that stores the IDs of records and their previous versions before they are updated or deleted.

It’s available in triggers that run before and after update, and before and after delete. You can use it to compare the old and new values of records during an update or to access deleted records by their ID in delete triggers.

This is useful for tracking changes or performing actions based on a record’s state before the current operation.

For example, if you set the opportunity amount, you don’t want another user to change it.

Even if it is editable, you can use trigger.oldMap to fetch the existing opportunity amount and check it with the new amount. If it does not match, prevent the record from being saved.

Here, we created a trigger on the opportunity object, and the event we created was a before update event.

Then I initiated a map with ID as key and sObject opportunity and assigned it as an oldMap. Then, I added a loop for each trigger and passed Trigger.new, which stores the new value users will update in the amount field.

In the for loop, I created the oldOpp variable to store the records of new opportunities we fetched using the get() method.

Then, an if condition is added to check whether the new opportunity amount equals the old one.

If not, we use the addError() method to throw an error message and restrict the record from being saved.

trigger OppoTrigger on Opportunity (before update) {
    
    Map<Id, Opportunity> oppoMap = Trigger.oldMap;

        for ( Opportunity newOpp : Trigger.new ) {
        Opportunity oldOpp = oppoMap.get ( newOpp.Id );
        if ( newOpp.Amount != oldOpp.Amount ) {
            newOpp.Amount.addError ( 'Amount cannot be changed' );
        }
    }
}

As you navigate to the opportunity record, you can see the number fields with the value of 4400.

Create an Apex Trigger in Salesforce

As I changed the value and tried to save the record, the error said we passed in an addError method, and the record was not saved.

Apex Triggers in Salesforce

So, these are some important context variables in an Apex Trigger in Salesforce.

Conclusion

I hope you have some idea of how to automate processes using Apex Triggers in Salesforce. Here, we learned what Apex triggers are, when to use them, and which trigger events are available in Salesforce.

Then I explained Apex trigger syntax, and we reviewed code for creating an Apex trigger in Salesforce.

Later on, we saw what trigger context variables are, their types, and how we can use them in Apex triggers to perform operations on records in the Salesforce database.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.