What are Triggers in Salesforce 

Apex Triggers in Salesforce are very useful in performing certain actions before or after a change occurs on the records. These actions are defined as code blocks and gets invoked when a DML operations happens. You can define triggers for standard objects that support triggers like Account, contact,Opportunity or some standard child objects, such as a CaseComment, and even custom objects. 

Triggers in Salesforce
Triggers in Salesforce

Now we have understood that whenever a DML operation happens a trigger will get executed if it has been defined to capture that DML operation. Let us see what are the different Data Manipulation Language(DML) operations which can invoke a trigger.

Triggers DML Operations

Syntax of Trigger

trigger_name : Name of the trigger you are writing
Object_name :
Object on which trigger is being written
events :
trigger events like beforeinsert,before update etc.


trigger trigger_name on object_name(event) {


//code

}

Trigger always has to be defined for a certain object.  If there are more that one event for a trigger then use multiple events separated by comma. Example :

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

//code 

}

Trigger Context Variables

Triggers in Salesforce have Context variables stored in System.Trigger class and are used to access run-time contexts.

Variable  Usage
isInsert Returns the value true if this trigger was fired as a result of  an insert operation
isUpdate Returns true if this trigger was fired as a result of an update operation
isDelete Returns true if this trigger was fired as a result of a delete operation
isBefore Returns true if this trigger was fired before any record got saved.
isAfter Returns true if this trigger was fired after all records got saved.
isUndelete Returns true if this trigger was fired after a record is restored from the Recycle Bin
new Returns a list of new versions of the sObject records.
newMap Returns a map of IDs to the new versions of the sObject records.
old Returns a list of old versions of the sObject records.
oldMap Return A map of IDs to the old versions of the sObject records.
size Provides the total number of records in a trigger invocation, both old and new.

Operations which do not invoke an Apex Trigger

Apex triggers in Salesforce are invoked by DML operations that the Java application server initiates or processes. There are many system bulk operations that do not invoke trigger. Let us see some examples :

  • Mass Address Updates
  • Renaming Picklists
  • Modifying custom fields data types
  • Cascading delete operations
  • Mass campaign status change
  • Cascade update of child records that are reparented
  • Mass approval request transfers
  • Mass email actions.

Workflow or Apex Triggers in Salesforce?

Have you ever wondered why do we use Apex trigger when we can update a field using Workflow or why do we even use workflow if we can do multiple DML operations just by written Apex triggers.

There are Pros and Cons everywhere so let’s see the major differences between a workflow and an Apex trigger.

Workflow Triggers
Workflows are point and click and do not require coding. Triggers are Code block written to perform certain actions.
Workflow rules cannot be used to perform DML operations We can perform up to 20 DML operations in one trigger.
Workflows action are done based on evaluation criteria and rule defined. Trigger works on DML operations
Workflow cannot be used to perform SOQL query Triggers can be used to perform SOQL query
Child record cannot be updated when a parent record in updated This is feasible using trigger
Workflow cannot be used to create new records We can create new records with workflow.
Workflow works only after certain action like insert, update Triggers works both before and after DML operations like beforeinsert, afterinsert

 If there is a simple field update or simple action which can be done by workflow it is better to not go for Apex trigger coding.

Triggers in Salesforce Examples

Let us see some to understand how triggers in Salesforce work.

  1. Suppose you want to make sure that the account name of the record being inserted is not present already and if it is already present an error message should pop up.
trigger DuplicateAccountCheck on Account (before insert)
{
List<account> acc =[Select id from account where account.name=:trigger.new[0].name];
if(acc.size()>0)
{
trigger.new[0].name.addError('This account Name is already present');
}
}

2.  There is an account which has more than 1 opportunity related to it. You want to update a checkbox field named Big deals on opportunity if the account gets updated.

trigger accountopp on Account (after update){
List<Opportunity> oppList = new List<opportunity>();
List<opportunity> oppList1 = new List<opportunity>();
for(Account acct: [SELECT Id,(SELECT Id,big_deals__c FROM Opportunities) FROM Account WHERE Id in: Trigger.new]){
If(acct.Opportunities.size()>0){
OppList.addAll(acc.opportunities);
}
}
for(Opportunity o:oppList){
o.big_deals__c=true;
oppList1.add(o);
}
update oppList1;
}

Best practices for Triggers

  • There should be only one trigger per object because if multiple triggers are written on an object you cannot control which trigger will execute before the other.
  • Make sure you Bulkify your code so handle a single record as we all bulk records.
  • Avoid using SOQL and DML statements inside for loop otherwise it will hit the governor limits
  • Use collections like Sets, Maps, List to use and store data.
  • Avoid hard coding Test classes written for the trigger otherwise you could face an issue during deployment as the same record might not be available in the other org.
  • Try Trailhead Modules for Apex Triggers for Practice.
  •  Read the important Salesforce Interview questions asked from triggers.
Use the below code to share the infographics on your site!
<a href='https://sfdcwisdom.com/triggers-in-salesforce/'><img src='https://i0.wp.com/sfdcwisdom.com/wp-content/uploads/2019/11/Triggers-in-Salesforce.png?resize=768%2C1920&ssl=1' alt='Triggers in Salesforce' 540px border='0' /></a></p>


1 Comment

Salesforce Interview questions you must know in-2020 - SFDC Wisdom · November 15, 2019 at 10:19 am

[…] Apex Trigger Blog for indepth and complete knowledge of […]

Did you Like the content? Let me know

%d bloggers like this: