You are on page 1of 12

Introduction:

A trigger is an Apex script that executes before or after changes occur to salesforce
records. These changes include operations like Insert, Update, Delete, Undelete,
Upsert.

When to use Triggers:

● An Apex Trigger is a stored procedure that is called whenever a record is


Inserted, Updated or Deleted. If any changes happen to any single or multiple
records, the Apex Trigger created on that Object will be fired.
● Use triggers to perform tasks that can’t be done using point & click tools in
Salesforce. If a task is possible using point & click tools then always prefer doing
that from them.
● Triggers are active by default when created and Salesforce automatically fires
active triggers when a specified database event occurs.
● 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.

Types Of Triggers:

● Before triggers: It is used to update or validate record values before saving 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.

Syntax & Trigger Events:

trigger TriggerName on ObjectName(trigger event)


{
//Code Block
}

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

● insert
● update
● delete
● upsert
● undelete

Trigger Context Variables

Variable Usage

Returns true if the current context for the


Apex code is a trigger, not a Visualforce
isExecuting
page, a Web service, or an
executeanonymous() API call.

Returns true if this trigger was fired due


isInsert
to an insert operation

Returns true if this trigger was fired due


isUpdate
to an update operation

Returns true if this trigger was fired due


isDelete
to a delete operation.

Returns true if this trigger was fired


isBefore
before any record was saved.

Returns true if this trigger was fired after


isAfter
all records were saved.

If a record is recovered from the recycle


isUndelete
bin it returns true.
Returns a list of the new versions of the
sObject records. This sObject list is only
new 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
newMap
available in before update, after insert,
after update, and after undelete triggers.

Returns a list of the old versions of the


old sObject records.This sObject list is only
available in update and delete triggers.

A map of IDs to the old versions of the


oldMap sObject records.This map is only
available in update and delete triggers.

The total number of records in a trigger


size
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 Use Salesforce CRM Effectively for Project Management?


Can update Can delete
Can change
original object original object
Trigger Event fields using
using an update using a delete
trigger.new
DML operation DML operation

beforeinsert Allowed. Not applicable. Not applicable.

Not allowed. A Allowed, but


runtime error is unnecessary. The
afterinsert thrown, as Allowed. object is deleted
trigger.new is immediately after
already saved. being inserted.

Not allowed. A Not allowed. A


beforeupdate Allowed. runtime error is runtime error is
thrown. thrown.
Not allowed. A
runtime error is
afterupdate thrown, as Allowed. Allowed.
trigger.new is
already saved.

Not allowed. A
runtime error is
thrown.
beforedelete Allowed. Not allowed.
trigger.new is not
available before
delete triggers.

Not allowed. A
runtime error is Not applicable. Not applicable.
thrown. The object has The object has
afterdelete
trigger.new is not already been already been
available after deleted. deleted.
delete triggers.

Not allowed. A
Allowed, but
runtime error is
unnecessary. The
thrown. trigger.old
afterundelete Allowed. object is deleted
is not available
immediately after
after undelete
being inserted.
triggers.
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

1. 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.lastname);

for(Contact con : [select lastName from contact where lastName 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.

2. 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.


● 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.

3. Trigger update before Example on Contact (before update)

{
list&lt;account&gt; acclist = new list&lt;account&gt;();
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 &amp;&amp; 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

4. 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.

5. 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.

6. 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;
}}

Basic trigger context Concept Clear example Code Snippet:

trigger AccountTrigger on Account (before insert, after insert, before update, after update,
before delete, after delete, after undelete) {

If(trigger.isInsert){
If(trigger.isBefore){
System.debug('Before---> NewList'+Trigger.New);
System.debug('Before---> OldList'+Trigger.Old);
System.debug('Before---> NewMap'+Trigger.NewMap);
System.debug('Before---> OldMap'+Trigger.OldMap);
}
If(trigger.isAfter){
System.debug('After---> NewList'+Trigger.New);
System.debug('After---> OldList'+Trigger.Old);
System.debug('After---> NewMap'+Trigger.NewMap);
System.debug('After---> OldMap'+Trigger.OldMap);
}
}
If(trigger.isUpdate){
If(trigger.isBefore){
System.debug('Before---> NewList'+Trigger.New);
System.debug('Before---> OldList'+Trigger.Old);
System.debug('Before---> NewMap'+Trigger.NewMap);
System.debug('Before---> OldMap'+Trigger.OldMap);
}
If(trigger.isAfter){
System.debug('After---> NewList'+Trigger.New);
System.debug('After---> OldList'+Trigger.Old);
System.debug('After---> NewMap'+Trigger.NewMap);
System.debug('After---> OldMap'+Trigger.OldMap);
}
}

If(Trigger.isDelete){
If(trigger.isBefore){
System.debug('Before---> NewList'+Trigger.New);
System.debug('Before---> OldList'+Trigger.Old);
System.debug('Before---> NewMap'+Trigger.NewMap);
System.debug('Before---> OldMap'+Trigger.OldMap);
}
If(trigger.isAfter){
System.debug('After---> NewList'+Trigger.New);
System.debug('After---> OldList'+Trigger.Old);
System.debug('After---> NewMap'+Trigger.NewMap);
System.debug('After---> OldMap'+Trigger.OldMap);
}
}

If(Trigger.isUnDelete){
If(trigger.isAfter){
System.debug('After---> NewList'+Trigger.New);
System.debug('After---> OldList'+Trigger.Old);
System.debug('After---> NewMap'+Trigger.NewMap);
System.debug('After---> OldMap'+Trigger.OldMap);
}
}

You might also like