20
NovDiwali Deal : Flat 20% off + 2 free self-paced courses + Free Ebook + $200 Voucher - SCHEDULE CALL
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:
Trigger trigger Name on sObject(Trigger event) { //logic }
Salesforce Training For Administrators & Developers
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:
A trigger is Apex code that executes before or after the following types of operations:
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. |
The following are lists of considerations about actions of different trigger events:
Read: Top 187 Salesforce Developer Interview Questions and Answers
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:
Example
{
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
Learn Salesforce in the Easiest Way
{ 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
Trigger. Old and trigger. New are update events in salesforce.
Read: Unleash the Future of Salesforce Developer: Exploring the Revolutionizing Frontier
Before Update
It’s going to store the set record before updating to the database.
{ 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
Example
{ 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
This is going to hold the records which are going to be deleted. These records are read only by operation.
Before Delete example
Read: Batch Apex Class in Salesforce - Level Up Your Salesforce Dev Skills
{ for(Account Acc:trigger.old) { acc.Name.addError('Account cannot be deleted'); } }
After Undelete
A map of IDs to the old version of the sObject records. Note that this map is only available in update and delete triggers.
{ 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'); } } }
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.
{ 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; }}
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!
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.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
An Ultimate Guide To Salesforce Business Analyst Certification 250.7k
Complete Advanced Administrator Salesforce Certification Guide [2023] 258.5k
An Ultimate Guide to Salesforce Controllers 5.3k
Salesforce Platform Developer 1 Exam Details You should Know! 328.5k
Top 7 Impactful Data Loaders Tools for Salesforce : Import & Export Data 261.7k
Receive Latest Materials and Offers on Salesforce Course
Interviews