Apex Trigger in Salesforce

Apex Trigger in Salesforce

Are you looking for the best advice on Apex Triggers in Salesforce to derive more value out of your Salesforce products? If your answer is in the affirmative, this blog on Salesforce Apex Triggers.

Let us pursue this informative journey by understanding about Triggers.

What is a Trigger?

A trigger is an Apex script that executes before or after certain events occur in DML, For example, before the object record is entered into the database or after the record has been deleted. Triggers allow you to carry out custom actions before or after changes to Salesforce records. A trigger is Apex code that is executed before or after the following types of operations such as Insert, update, delete and delete. 

Two types of Apex triggers

Before trigger

This trigger is used to update or verify the value of a record before it is saved in a database.

After trigger

This trigger is used to access values of the record ​​stored in a database and use this value to make changes to other records. After trigger records are in read-only format.

Bulky Trigger

By default, all triggers in Salesforce are bulky triggers. This means you can process many records simultaneously. Bulky triggers can handle  bulk operations and single-record updates, such as the following:

  • Data import
  • Mass Fraction
  • Bulk API calls
  • The recursive apex methods

Trigger Syntax

 trigger myAccountTrigger on Account (before insert, before update) {



  1.  myAccountTrigger – triggerName ( It is the name you would want to give your trigger).
  2. Account – Objectname (It is the object on which the action needs to be performed).
  3. before insert, before update – Trigger_events

Before insert: When using this event, the code block gets executed before a new record is inserted.

Before update: When you use this event, the code will get executed before a new record is updated in the object.

Trigger Context Variables:


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.


Returns true if this trigger was fired due to an insert operation


Returns true if this trigger was fired due to an update operation


Returns true if this trigger was fired due to a delete operation.


Returns true if this trigger was fired before any record was saved.


Returns true if this trigger was fired after all records were saved.


If a record is recovered from the recycle bin it returns trigger true.


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 before triggers.


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.


Returns a list of the old versions of the sObject records. This sObject list is only available in update and deletes triggers.


A map of IDs to the old versions of the sObject records. This map is only available in update and deletes triggers.


The total number of records in a trigger invocation.

Triggers in Salesforce vs. Workflow in Salesforce


  • It is an automated process that can shoot an action that is based on evaluation and rule criteria.
  • Performing DML operations in the workflow is not possible.
  • We can obtain a workflow over an object.
  • We can’t create a query from the database.


  • It is a piece of code which is executed either before or after a record is updated or inserted.
  • More than 15 DML operations can be used in a single trigger.
  • More than 20 SOQLs can be used from the database in a trigger.
  • We can access triggers across an object and related to that object.

Limitations of Workflows overcome by Triggers in Salesforce

  • Workflows are not able to create or update a separate object.
  • You can’t reference certain fields when using workflows.
  • You will not have your workflow doing more than just field updates and emails.


Triggers in Salesforce are called Apex Triggers. A trigger in Salesforce is an Apex code that is used to perform an operation before or after a record is operated.

Want to know more about triggers? Contact our certified Salesforce Consultants now!

How to Write a Test Class for Apex Trigger?

How to Write a Test Class for Apex Trigger?

The Apex testing framework makes sure that developers can write and execute tests for all the Apex Classes and triggers in the Force.com platform. In the testing framework, the code is tested and the testing code is coded in the sandbox environment and then deployed to production Org. 

Apex Test Class Best Practices

1. Use @isTest at the Top for all the test classes.

2. Always put assert statements for negative and positive tests.

3. Utilize the @testSetup method to insert the test data into the Test class that will flow all over the test class.

4. Always make use of Test.startTest() and Test.stopTest() doing this it will increase the governor limit of the salesforce. We also use this to increase the governor’s limit.

5. Use System.runAs() method to test the functionality in user Context.

6. Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.

7. Avoid Using Hard Coding Ids anywhere in test Class or any apex class.

8. Ensure that each class has a minimum of 75% coverage and also the main functionality has been covered. If possible increase code coverage up to 95%.

9.  All class methods must be tested for at least 200 records and keep the real scenarios in mind.

10. Only one Test.startTest() and Test.stopTest() statement can be in a method, and no of  Test.startTest() and Test.stopTest() statement in any test class depend upon the test methods.

Test Class Example


public class setOpportunityOwner 


    public TestMethod static void setOpportunityOwner_Method()


        Opportunity opp = New Opportunity();

        opp.name = ‘Hello’;

        opp.stageName = ‘Prospecting’;

        opp.CloseDate = Date.today();

        insert opp;

        Task tk = New Task();

        tk.WhatId = opp.Id;

        tk.Subject = ‘Other’;

        tk.status = ‘Not Started’;

        tk.description = ‘New  Work’;


        Database.SaveResult str = database.insert(tk , False);

        System.assertEquals(True, str.isSuccess());




Advantages of Apex Test Classes

  • You can use Test.isRunningTest() within your code to recognize that the context of the class is Test or not. 
  • You can use this condition with OR (||) operator to enable test classes to highlight inside the Code block.
  • Utilize @TestVisible annotation to identify private members and methods inside Test Class.

Salesforce Tasks in Apex

A task in Salesforce is defined as an assigned action that is required to be done by the user to whom the task is assigned. Tasks can be related to leads, campaigns, contacts, and contracts.

Difference between WhatID and WhoID in Task

WhatID in Salesforce – It represents object type things. It can easily relate to AccountID or an Opportunity ID. The WhatId refers to nonhuman objects like accounts, campaigns, opportunities, or custom objects. WhatId occurs in several different forms that means WhatId equals to the ID of a related object. The label for WhatID is Related To.

WhoID in Task – WhoID represents people things. It can easily relate to Lead ID or a Contact ID. It refers to human-like a lead and a contact. WhoID equals to a contact’s ID or a lead’s ID. The label for WhoID is Name.


The Apex testing framework is an innovative tool enables you to write and execute your Apex Code. Test class code is developed in a Sandbox environment and deployed to a production org. Apex unit tests make sure that your Apex classes and triggers perform as expected. By following the above practices, you can easily write Apex triggers and classes in Salesforce and hence make your system both manageable and Scalable.

In order to learn more about Apex Triggers, check our latest webinar video on 

Change Data Capture & Asynchronous Apex Triggers presented by Sachin Arora, the Scrum Master and Principal Solutions Architect at Cloud Analogy

Process Builder Vs Apex Triggers –  Choosing Between Automation Tools

Process Builder Vs Apex Triggers – Choosing Between Automation Tools

Process Builder Overview

Process Builder is a graphical representation of your process as you build it. It consists of

Criteria, Immediate and Scheduled Actions.

There are following things which can be done by process builder:

  • Create Records:In addition to updating a record, you can create a record and set the field values within the record.
  • Create Chatter Post:   Push a chatter update into Group or Feed.
  • Create an approval:Traditionally you needed a trigger to push a record into an approval process automatically. With Process builder, you can do this automatically based on criteria of the process.
  • Quickly consolidate Workflow:Quickly consolidate multiple workflow rules that in one process.
  • Call an Apex Class:You can now call an Apex class.

Trigger Overview

A trigger is the piece of code, that is executed Before or After a record is inserted or updated.

Usually, an APEX (code) based evaluation of criteria to set off a chain of events.These events execute the following types of operations

  • Insert
  • Update
  • Delete
  • Merge
  • Upsert
  • Undelete

In Apex Trigger you must have

  • Need to programming knowledge.
  • Need to design test classes to meet required test coverage.

But the main difference in process builder is you can not delete any record and can’t show any error. For these, you have to write Trigger code. For example:

Apex Limitations

  • Total number of records retrieved via SOQL queries                                       50,000
  • Total number of records retrieved by DML                                                        10,000
  • Total number of SOSL queries issued                                                                 100(Sync) | 200(Async)
  • Total number of SOSL queries issued                                                                 20
  • Total number of records retrieved by a single SOSL query                             2,000
  • Total number of DML statements issued                                                           150
  • Maximum number of characters for a trigger                                                   1 million

Process Builder Limitations

Editing: User can’t edit process once it has been activated.Therefore much like with flow, a new process needs to be created by cloning the initial process and making modifications to that cloned records.

Validation: Processes DO NOT  trigger Validation rule and can, therefore, invalidate data.

Deletion: The inactive process can’t be deleted for at least 12 hours after inactivation and do not appear in the Recycle Bin

Error Message: You can’t specify error messages when creating a process that doesn’t trigger as you can with flow or validation rules.

Formula help: When utilizing formula in criteria, there is no function help preview next to the syntax

Syntax: Pick-list fields are evaluated as text fields in process builder so that they won’t support any pick list formulas like ISCHANGED or ISNEW.

Apex Trigger Best Practices

  • Apex code must provide exception handling.
  • When query large data set use an SOQL FOR loop
  • Don’t use  SOSL and SOQL inside for loop.
  • Avoid Hard Coding IDs

Process Builder Best Practices

  • Check: To see if there are any workflows on the object doing the same things as the process. Also, verify no active Apex Trigger.
  • Avoid: Interviewing Apex, workflows, and processes together for the same process.
  • Document: Use the Description field to populate information such as when it was created by who and what the process does.Also, if processes work in conjunction with each other.
  • Test: And then test some more.Especially when you are first starting to use this please practice in the sandbox first.

There’s a lot of ability to impact users and data here if you do something wrong.

Now the question is Why Process Builder and how is it differ from trigger?

Process builder is fully customization. No code required here because we require lengthy logic and record to complete and fulfill the requirement or if we using process builder it will take less time to complete the requirement.

It has some benefits over the trigger:

Scenario I

Populate a lookup field on record update:

Traditionally required a trigger and It can be done easily with process builder.

The issue is Multi layer lookup logic- i.e. multiple / nested maps of related data required in the trigger.

          Process builder Trigger Traditionally been something that requires a Trigger. Process builder allows administrator can do this without the use of the code.
Scenario II

Set an Account Owner based on Record criteria

Process builder


Process builder can be used to assign ownership of records based on criteria in the object.
Scenario III

Post a chatter message based on record criteria

Process builder


Process builder can be used to post to chatter based on record criteria.
Scenario IV

Submit a Quote for Approval when Opportunity Stage= Proposal

Process builder Trigger Requires 2 Processes one to Update the Quote based on the opportunity stage and another to submit the quote for the approval when the criteria on the quote had been met.
Scenario V

Launch a Flow via record criteria vs a button or link.

Process builder


Process builder can be used to set record criteria and then launch a trigger ready flow.
Scenario VI

Clone an opportunity and change the field values

Process builder


Although Process builder can create a new record it can’t reference any of the values from the cloned opportunity without the use of a flow to capture the opportunity values.

Let’s have a look on given Process builder example :

Allow Contact to copy Current User Address in Contact Address and Account Billing Address only when any address field(Street, Country, state )is blank/NULL.

Step 1:

Make your Process-builder on Contact Object. Provide the criteria as Contact.Mailing Street (IS NULL = FALSE) and likewise for every address fields of Contact and Opportunity.

Step 2:

In “Immediate Action” give reference of Mailing Country to that of Contact.Owner.Country and Activate your Process as:

 Step 3:

Now test this process builder in your org by leaving any address field blank in your org.

Step 4:

After leaving Contact address blank here is the address which got autofilled same as contact’s owner address. Similarly you can test this for your Contact’s Account.

This is the reason for using Process builder rather than using Apex. But  in some scenarios you’ll have to write trigger code where process builder can’t be.

For example:

Create a checkbox field “SAME COUNTRY AS USER & COMPANY”. Throw error when a Contact is getting inserted in Salesforce having Country same as User country and Company country.

Above example can’t be done via Process builder since this do not allow you to throw error while inserting Contact.
Create  Checkbox field named “SAME COUNTRY AS USER & COMPANY” on Contact.

public class SameUserAndCompanyCountryContact {

public static void sameCountry(List<Contact> conList){

   User user = new User();

   user = [SELECT Id , Country , CompanyName from User where Id =:UserInfo.getUserId()];


Organization orgDetails = [ SELECT Name , Country , Address from Organization where Name =: user.CompanyName];


for(Contact con : conList) {

  if(con.MailingCountry == user.Country && con.MailingCountry == orgDetails.Country){

   con.addError('Country of Company and User is same as country of Contact trying to insert');

     con.Same_Country_As_User_And_Company__c = True;




trigger ErrorOnSameCountry on Contact (before insert){
  List<Contact> conList = Trigger.new;
     if(conList!=null) {


Although the usage of process builder over apex trigger or vice versa is dependent on various other factors too, such as:

  • Complexity Of Codes.
  • Programmatic Logics.
  • Rapid Iteration In Process Builder Can Be Challenging.
  • Unit Test Considerations.