Our Support: During the COVID-19 outbreak, we request learners to CALL US for Special Discounts!

- Salesforce Blogs -

What Is Trigger In Salesforce?

What Is Trigger In Salesforce?

A trigger is an Apex script that executes before or after specific data manipulation language (DML) events occur, such as before object records are inserted into the database, or after records have been deleted. Triggers enable you to perform custom actions before or after changes to Salesforce records. A trigger is Apex code that executes before or after the following types of operations like insert, update, and delete.

There Are Two Types Of Triggers:

  • Before triggers: It is used to update or validate record values before saved to the database.
  • After triggers: It is used to access values of the record that are stored in the database and use this value to make changes with other records.After trigger records are read-only.
Trigger trigger Name on sObject(Trigger event)
{
//logic
}

Bulky Trigger

Salesforce Training For Administrators & Developers

  • No cost for a Demo Class
  • Industry Expert as your Trainer
  • Available as per your schedule
  • Customer Support Available

All triggers are bulk triggers by default and can process multiple records at a time. You should always plan on processing more than one record at a time. Bulk triggers can handle both single record updates and bulk operations like:

  • Data import
  • com Bulk API calls
  • Mass actions, such as record owner changes and deletes
  • Recursive Apex methods and triggers that invoke bulk DML statements

A trigger is Apex code that executes before or after the following types of operations:

  • insert
  • update
  • delete
  • merge
  • upsert
  • undelete

Trigger Context Variables

Variable Usage
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
isUpdate Returns true if this trigger was fired due to an update operation
isDelete Returns true if this trigger was fired due to a delete operation.
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 If a record is recovered from the recycle bin it returns trigger true.
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 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.

Actions of Different Trigger Events

The following are lists of considerations about actions of different trigger events:

Read: How to Set and List Methods in Salesforce Apex?
Trigger Event Can change fields using trigger.new Can update original object using an update DML operation Can delete original object using a delete DML operation
beforeinsert Allowed. Not applicable. Not applicable.
afterinsert Not allowed. A runtime error is thrown, as trigger.new is already saved. Allowed. Allowed, but unnecessary. The object is deleted immediately after being inserted.
beforeupdate Allowed. Not allowed. A runtime error is thrown. Not allowed. A runtime error is thrown.
afterupdate Not allowed. A runtime error is thrown, as trigger.new is already saved. Allowed. Allowed.
beforedelete Not allowed. A runtime error is thrown. trigger.new is not available before delete triggers. Allowed. Not allowed.
afterdelete Not allowed. A runtime error is thrown. trigger.new is not available after delete triggers. Not applicable. The object has already been deleted. Not applicable. The object has already been deleted.
afterundelete Not allowed. A runtime error is thrown. trigger.old is not available after undelete triggers. Allowed. Allowed, but unnecessary. The object is deleted immediately after being inserted.

Insert Operation Before Insert:

  • This trigger will be fried when a new record is going to be saved in the database.
  • In before insert, trigger. New stores a new list of records which is going to be inserted.

Example

Trigger Duplicate Name on Contact (before insert, before update)

{
   set<String> lastName = new set<String>();
   set<String> setname = new set<String>();
   for(Contact con : Trigger.new)
   {
          lastName.add(con.email);

    }

    for(Contact con : [select lastName from contact where email in : lastName])
   {
          setname.add(con.lastName);
    }

   if(Trigger.isInsert||Trigger.isUpdate)
     for(contact a:trigger.new)
     {
         if(setname.contains(a.lastName))
        {
                 a.lastName.adderror('This email already exists');
          }
     }
}

After Insert

  • After insert trigger will be fired after new record inserted successfully in database.
  • New is going to hold a new record which is inserted into the database.
  • After insert trigger is read only operation. We can do DML operations on new records which are inserted into the database.

Learn Salesforce in the Easiest Way

  • Learn from the videos
  • Learn anytime anywhere
  • Pocket-friendly mode of learning
  • Complimentary eBook available

Trigger After Insert Example on Account (after insert)

{
for(Account acc: Trigger.new)
{
Account oldAcc = Trigger.oldMap.get(acc.Id);
if(oldAcc.phone != acc.phone)
{
List<Contact> conList = [ SELECT Id, AccountId, phone from  Contact where AccountId = :acc.Id];
List<Contact> newids = new List<Contact>();
for(Contact con: conList)
{
if(con.phone != acc.phone)
{
con.phone = acc.phone;
newids.add(con);
}
}
if (!newids.isEmpty())
{
update newids;
}
}
}
}

Update Event There are two types of events

  • Before update
  • After Update

Trigger. Old and trigger. New are update events in salesforce.

Read: Salesforce Lightning Interview Questions and Answers
  • New: Trigger. New is going to hold the list of records which going to be updated.
  • Old: Trigger. Old is going to hold the set of old values which are going to be updated.

Before Update

It’s going to store the set record before updating to the database.

Trigger update before Example on Contact (before update)

{
list<account> acclist = new list<account>();
for(contact acc:trigger.old){
account c = new account();
c.Name=acc.lastname;
c.Phone=acc.phone;
acclist.add(c);
}
insert acclist;
}

After update

  • After the update trigger will be fired when the changes that we have made are saved to the database.
  • In the after update trigger operation we can only read the data from trigger.
  • If we want to make any changes we need to perform DML operation.

Example

Trigger update Contact  on Account (after update)

{
if(trigger.IsAfter && trigger.IsUpdate){
set<id>ids = new set<id>();
list<contact>conlist = new list<contact>();
for(account a:trigger.new){
ids.add(a.id);
list<contact>con =[select id,phone,lastName,account.phone from contact where accountid in:ids];
for(contact c:con){
c.Phone=c.account.phone;
conlist.add(c);
}
update conlist;
}
}
}

Delete Event There are two events in delete

  • Before Delete
  • After Delete

Trigger. Old

This is going to hold the records which are going to be deleted. These records are read only by operation.

Before Delete example

Read: Create Salesforce Application, Objects, Tabs & Schema Builder

Trigger Account Delete on Account (before delete)

{
for(Account Acc:trigger.old)
{
acc.Name.addError('Account cannot be deleted');
}
}

After Undelete

  • When we are undeleting records from the recycle bin after undeleting operation required.
  • New is going to store the record which is undeleting from the recycle bin.

Trigger.newMap and Trigger.oldMap

Trigger.oldMap

A map of IDs to the old version of the sObject records. Note that this map is only available in update and delete triggers.

Trigger Map Demo on Account (before update)

{
Map<Id,account> accMap = new Map<Id,account>();
accMap = trigger.oldMap;
for(account acc : trigger.new)
{
account oldvalue = new account();
oldvalue = accMap.get(acc.Id);
if(acc.phone != oldvalue.phone)
{
acc.phone.addError('Phone cannot be changed');
}
}
}

Trigger.newMap:

A map of IDs to the new version of the sObject records. Note that this map is only available in before update, after insert and after update triggers.

Trigger update contact Phone on Account (before update)

{
if(trigger.isbefore && trigger.isupdate){
map<id,account> mapcon = trigger.newmap;
list<contact> cont = new list<contact>();
list<contact> con = [select id,phone,accountid from contact where accountid in : mapcon.keyset()];
for(contact c : con){
c.phone = mapcon.get(c.accountid).phone;
cont.add(c);
}
update cont;
}}

Summary

Apex triggers can help you to perform customized operations on a database. With this blog, we have learned a few facts about Trigger in Salesforce. If you still have any query, you can signup with JanBaskTraining to more or simply drop a query below in the comment box! Happy learning!



Salesforce Tutorial Overview


    Janbask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


Comments

Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

2 days 05 Aug 2020

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

-0 day 03 Aug 2020

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

14 days 17 Aug 2020

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

4 days 07 Aug 2020

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

1 day 04 Aug 2020

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

4 days 07 Aug 2020

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

2 days 05 Aug 2020

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

11 days 14 Aug 2020

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation

Upcoming Class

4 days 07 Aug 2020

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks

Upcoming Class

2 days 05 Aug 2020

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning

Upcoming Class

13 days 16 Aug 2020

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop

Upcoming Class

4 days 07 Aug 2020

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews