Today's Offer - Salesforce Certification Training - Enroll at Flat 10% Off.

- Salesforce Blogs -

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 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, delete 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 record.After trigger records are read-only.



Trigger trigger Name on sObject(Trigger event)

{

//logic

}

  Bulky Trigger

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

salesforce Curriculum

Read: How To Get A Job In Salesforce Without Experience?

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

Context Variable

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

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

  salesforce quiz Insert Operation Before Insert:

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

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 insert successfully in data base.
  • New is going to hold new record which is inserted to database.
  • After insert trigger is read only operation. We can do DML operation on new record which inserted to data base.

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 events

  • Before update
  • After Update

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

Trigger. New

Read: What is Salesforce Architecture? Tutorial Guide for Beginners

Trigger. New is going to hold the list of records which going to be update.

Trigger. Old

Trigger. Old is going to hold the set of old values which going to be update.

Before Update

It’s going to store the set record before update to 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 update trigger will be fired when the changes that we have made are saved to data base.
  • In the after update trigger operation we can only read the data from trigger.
  • If we want to do any changes we need to perform DML operation.

Example

Read: Top 50 Salesforce Interview Questions and Answers

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 delete. These records are read only operation.

Before Delete example

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 record from recycle bin after undeletes operation required.
  • New is going to store the record which undeleting from 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;
}}

Read: Salesforce Service Cloud Certification Study Guide For Beginner

Salesforce Tutorial Overview


    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

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

Upcoming Class

-1 day 14 Nov 2019

DevOps

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

Upcoming Class

0 day 15 Nov 2019

Data Science

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

Upcoming Class

0 day 15 Nov 2019

Hadoop

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

Upcoming Class

1 day 16 Nov 2019

Salesforce

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

Upcoming Class

-1 day 14 Nov 2019

QA

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

Upcoming Class

18 days 03 Dec 2019

Business Analyst

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

Upcoming Class

0 day 15 Nov 2019

SQL Server

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

Upcoming Class

4 days 19 Nov 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews