Salesforce Trigger Realtime Scenario



Triggers In Salesforce Apex Programing:
=======================================

1.Trigger is a Custom Apex code which will Execute/Fire Automaticaly.
2.On Certain Events & those Events are Our DML operations(Insert/Update/Delete/Undelete).
3.Trigger can fire in two Was Before & After.
4.Each Trigger is Directly Associted with The Object(Standard & Custom).
5.We can write One or More Trigger On an Object.
6.As we can not control the Execution of Multiple Trigger so it is
  Best Practice to write "Single" Trigger Per Object.

Types of Triggers:
====================
1.Before Trigger : Before complisition of DML Operation.
2.After Trigger : After complistion DML Operation

Syntax For Trigger:
=====================
trigger <Triggername> on <ObjectName> (<Event List>) {

}

Example:
---------

Trigger MyAccountTrigger On Account (Event List){
}

Trigger MyPositionTrigger on Position__c (Event List){
}

Trigger Events In Salesforce:
===============================
1.Event is a situation which will deside when your trigger will get Executed.
2.One Event should be Present in Trigger.
3.We need to seprate the event by comma.

Types Of Event:
================
1.Before Insert.
----------------
This Event will Fire the Trigger Before Inserting The Record in an Object.

2.Before Update.
----------------
This Event will Fire the Trigger Before Updating The Record in an Object.

3.Before Delete.
----------------
This Event will Fire the Trigger Before deleting The Record in an Object.

4.After Insert.
----------------
This Event will Fire the Trigger After Inserting The Record in an Object.

5.After Update.
----------------
This Event will Fire the Trigger After Updating The Record in an Object.
6.After Delete.
----------------
This Event will Fire the Trigger After deleting The Record in an Object.

7.After Undelete.
-----------------
This Event will Fire the Trigger After Undeleting The Record in an Object.

Example with Event In Trigger.
===============================
Trigger myAccountTrigger on Account(Before Insert,Before Update,Before Delete,
                                    After Insert,After Update,After Delete,After Undelete){
//Trigger Logic.
}

trigger myPositionTrigger on Position__c (before insert,before update,before delete,
                                          After insert,After Update,After Delete,After Undelete) {
                                              
           //Trigger Logic                                   
}

Trigger Context Variable:
==========================
1.Upon writing the Trigger Logic inside the trigger we need to segrigate 
  the code on the basis of Event so for doing the same we need  Trigger Context Variable.
2.Return Type Of COntext Variable is always "Boolean".
3.We can Identify the current status by using Trigger Context Variable

1.Boolean Trigger.IsExecuting
------------------------------
Return True if the current context if of Triiger.

2.Boolean Trigger.IsBefore
---------------------------
3.Boolean Trigger.IsAfter
---------------------------
4.Boolean Trigger.IsInsert
---------------------------
5.Boolean Trigger.IsUpdate
----------------------------
6.Boolean Trigger.isDelete
-----------------------------
7.Boolean Trigger.IsUndelete.

Syntax of Trigger with COntext variable:
=========================================
trigger myPositionTrigger on Position__c (before insert,before update,before delete,After insert,After Update,After Delete,After Undelete) {
    /*Add Trigger Context Variable*/
    if(Trigger.IsBefore && Trigger.IsInsert){
        system.debug('I AM IN BEFORE INSERT ');
    }
    If(Trigger.IsAfter && Trigger.IsInsert){
        system.debug('I AM In AFTER INSERT');
    }
    If(Trigger.IsBefore && Trigger.isUpdate){
        system.debug('I AM IN BEFORE UPDATE ');
    }
    If(Trigger.IsAfter && Trigger.IsUpdate){
        system.debug('I AM In AFTER UPDATE');
    }
    If(Trigger.IsBefore && Trigger.IsDelete){
        system.debug('I AM IN BEFORE DELETE ');
    }
    If(Trigger.IsAfter && Trigger.IsDelete){
        system.debug('I AM In AFTER DELETE');
    }
    If(Trigger.IsAfter && Trigger.IsUndelete){
        system.debug('I AM IN AFTER UNDELETE');
    }
    
}

8.Trigger.New[New Set of Record]
==================================
Trigger.New : is a List collection which contains the Current context Record(New).
Trigger.New : Will hold The data in the form of List Collection.

List<SobjectName> = Trigger.New
Note
-----
1.Trigger.New will be avilabe for Both "Insert & Update" operation.

Before           After
   -------------------------- 
    Insert           Insert
Update           Update


Trigger.New is Not avilable for "Delete" operation.


9.Trigger.Old [Existing Set of Record]
=======================================
Trigger.Old : is a List collection which contains the Old Set of Record/ existing record in Object.
Trigger.Old : Will hold The data in the form of List Collection.

List<SobjectName> = Trigger.Old
Note
-----
1.Trigger.Old will be avilabe for Both "Update / Delete / Undelete" operation.

Before           After
   -------------------------- 
    Update           Update
Delete           delete
                 Undelete.
 
Trigger.New is Not avilable for "Insert" operation.

Trigger.New is Not avilable for "Delete" operation.
10.Trigger.NewMap
==================
Trigger.NewMap : contains Current COntext of Data(New Set of Data) in the form of
MAP Collection.

Key   : RecordId
Value : Whole Record.
1.Trigger.NewMap will Not avilable for Before Trigger.
2.Trigger.NewMap will allways avilable in "After Insert" & "After Update"

11.Trigger.OldMap
==================
Trigger.OldMap : It contains Old Set of Record.but
in the form of MAP collection.
Trigger.ildMap is Present in All Update & Delete Operation.

Bulkification trigger:
========================
1.Upon creating a Trigger always write the logic in such a way that it should be able to Process.
  Multiple Records.
2.Always use Context Variable.
3.always Use Enhanced For loop to rotate the Collection.


Example of Trigger.
=====================
1.Create a Trigger on Lead Object which should validate the Lead Record
  To Make Lead Record Email Id & Contact Number Manadatory.
  
  Object Name : Lead.
  Event : Before Insert & Before Update
  

Class Code:
===========
trigger MyLeadTrigger on Lead (before insert,before Update) {
    //step2 Write Context Variable
    if(Trigger.isBefore && Trigger.isInsert){
        //step 3 Itrate The context Variable in for loop.
        system.debug('New Record==> ' +Trigger.New);
        for(Lead myldRec : Trigger.New){
            if(myldRec.Email == null){
                //use AddError Method from salesforce
                myldRec.AddError('Email Id is Manadatory');
                //myldRec.Email.AddError('Email Id is Manadatory');
            }
            else if(myldRec.MobilePhone == null){
                myldRec.MobilePhone.AddError('Mobile Number is Manadatory');
            }
        }
    }
    If(Trigger.IsBefore && Trigger.IsUpdate){
        //step 3 Itrate The context Variable in for loop.
        system.debug('New Record==> ' +Trigger.New);
        for(Lead myldRec : Trigger.New){
            if(myldRec.Email == null){
                //use AddError Method from salesforce
                myldRec.AddError('Email Id is Manadatory');
                //myldRec.Email.AddError('Email Id is Manadatory');
            }
            else if(myldRec.MobilePhone == null){
                myldRec.MobilePhone.AddError('Mobile Number is Manadatory');
            }
        }
    }
  
Optimized Way
===============
trigger MyLeadTrigger on Lead (before insert,before Update) {
    //step2 Write Context Variable
    if(Trigger.isBefore && (Trigger.isInsert || Trigger.IsUpdate)){
        //step 3 Itrate The context Variable in for loop.
        system.debug('New Record==> ' +Trigger.New);
        for(Lead myldRec : Trigger.New){
            if(myldRec.Email == null){
                //use AddError Method from salesforce
                myldRec.AddError('Email Id is Manadatory');
                //myldRec.Email.AddError('Email Id is Manadatory');
            }
            else if(myldRec.MobilePhone == null){
                myldRec.MobilePhone.AddError('Mobile Number is Manadatory');
            }
        }
    }
}

Trigger Example 2:
===================
create a Trigger On Account Object to Prevent the deletion of Account Record
for Below Condition.

Account:Active__c == Yes : then Donot allow to delete the Account.

Object : Account.
Event  : Before Delete
context Variable : Trigger.Old

trigger myAccountTrigger on Account (Before Insert,Before Update,Before Delete,After Insert,After Update,After Delete,After Undelete) {
    //step1 : add Context Variable for specific event.
    if(Trigger.IsBefore && Trigger.IsDelete){
        system.debug('in my Before Delete event');
        system.debug('My Record==> ' +Trigger.Old);
        //list<Account> mylstAcc = Trigger.Old;
        //system.debug('My mylstAcc==> ' +mylstAcc);
        for(Account myAcc : Trigger.Old){
            if(myAcc.Active__c == 'Yes'){
                myAcc.AddError('You are Not Allowed to Delete The Active Account');
            }
        }
        
    }
}

Execute:
=========
Try to delete any Active Account Record from Account Object

Trigger Example 3:
===================
Create a Trigger on Account Object To Assign The Annuval Revenue Based on Industry.

Industry Name             Annuval Revenue
==========================================
Banking                   60,00,000
Finance                   70,00,000
Insurance                 80,00,000
Education                 90,00,000

Event : Before Insert & Before Update.

Class Code:
------------
trigger myAccountTrigger on Account (Before Insert,Before Update,Before Delete,After Insert,After Update,After Delete,After Undelete) {
    If(Trigger.IsBefore && (Trigger.IsInsert || Trigger.IsUpdate)){
        for(Account accRec : Trigger.New){
            
            if(accRec.Industry == 'Banking'){
                accRec.AnnualRevenue = 6000000;
            }
            else if(accRec.Industry == 'Finance'){
                accRec.AnnualRevenue = 7000000;
            }
            else if(accRec.Industry == 'Insurance'){
                accRec.AnnualRevenue = 8000000;
            }
            else if(accRec.Industry == 'Education'){
                accRec.AnnualRevenue = 9000000;
            }
            else {
                accRec.AnnualRevenue = 1000000;
            }
        }
    }
    //step1 : add Context Variable for specific event.
    if(Trigger.IsBefore && Trigger.IsDelete){
        system.debug('in my Before Delete event');
        system.debug('My Record==> ' +Trigger.Old);
        //list<Account> mylstAcc = Trigger.Old;
        //system.debug('My mylstAcc==> ' +mylstAcc);
        for(Account myAcc : Trigger.Old){
            if(myAcc.Active__c == 'Yes'){
                myAcc.AddError('You are Not Allowed to Delete The Active Account');
            }
        }
        
    }
}

Assingment:
============
Write a Trigger on Lead Object When Lead Source Is Web Then Map Rating as Hot.

Trigger Example 4:
===================
Create a trigger on Account object when a New Account is Inserted 
Then Automaticaly create Associated Contact record with
Contact LastName as Account Name.

Object Name : Account.
Event Name : After Insert / After Update.

Class Code:
============
trigger myAccountTrigger on Account (Before Insert,Before Update,Before Delete,After Insert,After Update,After Delete,After Undelete) {
    If(Trigger.IsBefore && (Trigger.IsInsert || Trigger.IsUpdate)){
        for(Account accRec : Trigger.New){
            
            if(accRec.Industry == 'Banking'){
                accRec.AnnualRevenue = 6000000;
            }
            else if(accRec.Industry == 'Finance'){
                accRec.AnnualRevenue = 7000000;
            }
            else if(accRec.Industry == 'Insurance'){
                accRec.AnnualRevenue = 8000000;
            }
            else if(accRec.Industry == 'Education'){
                accRec.AnnualRevenue = 9000000;
            }
            else {
                accRec.AnnualRevenue = 1000000;
            }
        }
    }
    //step1 : add Context Variable for specific event.
    if(Trigger.IsBefore && Trigger.IsDelete){
        system.debug('in my Before Delete event');
        system.debug('My Record==> ' +Trigger.Old);
        //list<Account> mylstAcc = Trigger.Old;
        //system.debug('My mylstAcc==> ' +mylstAcc);
        for(Account myAcc : Trigger.Old){
            if(myAcc.Active__c == 'Yes'){
                myAcc.AddError('You are Not Allowed to Delete The Active Account');
            }
        }
        
    }
    
    If(Trigger.IsAfter && (Trigger.IsInsert || Trigger.IsUpdate)){
        List<Contact> contactToInsert = New List<Contact>();
        for(Account lstAcc : Trigger.New){
           contact con = New Contact();
           con.FirstName = lstAcc.Name;
           con.LastName = lstAcc.Name;
           con.AccountId = lstAcc.Id;
           contactToInsert.add(con);
        }
        if(!contactToInsert.isEmpty()){
            insert contactToInsert;
        }
    }
}

Assingment.
-------------
Create a trigger on Position object when a New Position is Inserted 
Then Automaticaly create Associated Candidate record with
Candidate Name  as Position Name.

Example: 5
============
1.Find The Count of Contact on Account & Update the count on Account Object Record.
2.Contact Rollup Summary Trigger.

Object Name: contact
----------------------
Event : After Insert & After Delete.
-------------------------------------

Step 1:
--------
Create a Field on Account Object with Number Data Type.
Label : No Of Contact.

Class Code:
============
trigger MyContactTrigger on Contact (After Insert,After Delete) {
    List<Contact> contactContaextList = New List<Contact>();
    Set<Id> myAccountId = New Set<Id>();
    List<contact> mynewConlist = New List<contact>();
    
    if(Trigger.IsAfter){
        if(Trigger.IsDelete){
            contactContaextList = Trigger.Old; //Adding Old Set of Record in List
            system.debug('my Contact Count OLD==> ' +contactContaextList);
        }
        else{
            contactContaextList = Trigger.New; // Adding New Set of record in List
             system.debug('my Contact Count NEW==> ' +contactContaextList);
        }
        
        for(contact con : contactContaextList){
            if(con.AccountId != null){
                myAccountId.add(con.AccountId);
                system.debug('myAccountId Set==> ' +myAccountId);
            }
        }
        List<Account> myaccRec = [Select Id,Name,No_of_Contacts__c,
                                  (select Id,Name From Contacts) from Account Where Id IN:myAccountId];
        
        system.debug('myaccRec=== > ' +myaccRec);
        for(Account acc :myaccRec){
            mynewConlist = acc.contacts;  //Adding the Contact in new List of contacts
            if(!mynewConlist.IsEmpty()){
                acc.No_of_Contacts__c = mynewConlist.size(); //Adding The Size to Update The coount
            }
        }
        update myaccRec;
    }

Trigger Handler Factory Or Trigger Handler Class.
==================================================
1.Trigger Should always be a Logicless trigger in Salesforce.
2.Every Trigger Logic should be Written in a Apex class called as "Trigger Handler Class"

Structure Of Trigger Handler Class:
======================================
Trigger:
---------
trigger myAccountTrigger on Account (Before Insert,Before Update,Before Delete,After Insert,After Update,After Delete,After Undelete){
   
    //Define Context Variable to Call the Trigger Logic.
    
    if(Trigger.IsBefore && Trigger.isInsert){
        
        AccountTriggerHandler.BeforeInsert();
    }
    if(Trigger.IsBefore && Trigger.IsUpdate){
        
        AccountTriggerHandler.BeforeUpdate();
    }
    if(Trigger.IsBefore && Trigger.IsDelete){
        
        AccountTriggerHandler.BeforeDelete();
    }
    if(Trigger.isAfter && Trigger.IsInsert){
        
        AccountTriggerHandler.AfterInsert();
    }
    if(Trigger.IsAfter && Trigger.IsUpdate){
        
        AccountTriggerHandler.AfterUpdate();
    }
    If(Trigger.isAfter && Trigger.isDelete){
        
        AccountTriggerHandler.AfterDelete();
    }
    if(Trigger.IsAfter && Trigger.IsUndelete){
        
        AccountTriggerHandler.AfterUndelete();
    }
}

Handler CLass:
----------------
/*
 @Author : Khumed Khatib
 @ClassName : AccountTriggerHandler.
 @Date : 02/05/2024.
 @Description : Class Of Account Trigger Logic
*/
public class AccountTriggerHandler {
    //Method for BeforeInsert Logic
    public static void BeforeInsert(){
        system.debug('In My Before Insert Method');
    }
     //Method for BeforeUpdate Logic
    Public Static void BeforeUpdate(){
        system.debug('In My Before Update Method');
    }
     //Method for BeforeDelete Logic
    Public static void BeforeDelete(){
        
    }
     //Method for AfterInsert Logic
    public static void AfterInsert(){
        system.debug('In My After Insert Method');
    }
     //Method for AfterUpdate Logic
    public static void AfterUpdate(){
        system.debug('In My After Update Method');
    }
     //Method for AfterDelete Logic
    public static void AfterDelete(){
        
    }
     //Method for AfterUndelete Logic
    public static void AfterUndelete(){
        
    }
}

=======================================================

Class Code:
------------
trigger myAccountTrigger on Account (Before Insert,Before Update,Before Delete,After Insert,After Update,After Delete,After Undelete){
   
    //Define Context Variable to Call the Trigger Logic.
    
    if(Trigger.IsBefore && Trigger.isInsert){
        
        AccountTriggerHandler.BeforeInsert(Trigger.New);
    }
    if(Trigger.IsBefore && Trigger.IsUpdate){
        
        AccountTriggerHandler.BeforeUpdate(Trigger.New);
    }
    if(Trigger.IsBefore && Trigger.IsDelete){
        system.debug('in My Trigger');
        AccountTriggerHandler.BeforeDelete(Trigger.Old);
    }
    if(Trigger.isAfter && Trigger.IsInsert){
        
        AccountTriggerHandler.AfterInsert();
    }
    if(Trigger.IsAfter && Trigger.IsUpdate){
        
        AccountTriggerHandler.AfterUpdate();
    }
    If(Trigger.isAfter && Trigger.isDelete){
        
        AccountTriggerHandler.AfterDelete();
    }
    if(Trigger.IsAfter && Trigger.IsUndelete){
        
        AccountTriggerHandler.AfterUndelete();
    }
}

------------------------
/*
 @Author : Khumed Khatib
 @ClassName : AccountTriggerHandler.
 @Date : 02/05/2024.
 @Description : Class Of Account Trigger Logic
*/
public class AccountTriggerHandler {
    //Method for BeforeInsert Logic
    public static void BeforeInsert(List<Account> lstAccount){
       updateAnnuvalRevenue(lstAccount);
    }
     //Method for BeforeUpdate Logic
    Public Static void BeforeUpdate(List<Account> lstAccount){
        //Use of Label for Stop / Start the Logic
        if(system.label.IsActiveTriggerMethod == 'Yes'){
            system.debug('In My label');
            updateAnnuvalRevenue(lstAccount);
        }
    }
     //Method for BeforeDelete Logic
    Public static void BeforeDelete(list<Account> MyaccList){
        system.debug('MyAccList====>  ' +MyaccList);
        for(Account myAcc : MyaccList){
             if(myAcc.Active__c == 'Yes'){
                myAcc.AddError('You are Not Allowed to Delete The Active Account');
            }
        }
    }
     //Method for AfterInsert Logic
    public static void AfterInsert(){
        system.debug('In My After Insert Method');
    }
     //Method for AfterUpdate Logic
    public static void AfterUpdate(){
        system.debug('In My After Update Method');
    }
     //Method for AfterDelete Logic
    public static void AfterDelete(){
        
    }
     //Method for AfterUndelete Logic
    public static void AfterUndelete(){
        
    }
    
    /*All the Other methods for code Optimization*/
    
    public static void updateAnnuvalRevenue(List<Account> NewAccountlst){
        system.debug('My Logic of Annuvalrevenue' +NewAccountlst);
        for(Account accRec : NewAccountlst){
            
            if(accRec.Industry == 'Banking'){
                accRec.AnnualRevenue = 6000000;
            }
            else if(accRec.Industry == 'Finance'){
                accRec.AnnualRevenue = 7000000;
            }
            else if(accRec.Industry == 'Insurance'){
                accRec.AnnualRevenue = 8000000;
            }
            else if(accRec.Industry == 'Education'){
                accRec.AnnualRevenue = 9000000;
            }
            else {
                accRec.AnnualRevenue = 1000000;
            }
        }
    }
    
}


Trigger Example Scenario:
==========================
Create a Number of contacts which are equle to the Number which we will
enter in the Number of Loction field on the Account Object.

Solution:
=========
Create a Custom field called "Number of Location" on Account object 
[DataType = Number]

Object : Account.
Event  : After Insert.

Class Code:
------------
public static void contactCreationfromLocation(List<Account> NewAccountLst){
List<Contact> lstContact = New List<Contact>();
//Create a Map with Id & Decimal
Map<Id,Decimal> myMapAcc = New Map<Id,Decimal>();
for(Account acc : NewAccountLst){
myMapAcc.put(acc.Id , acc.NumberofLocations__c);
system.debug('my MAP ==> ' +myMapAcc);
}
if(myMapAcc.size() > 0 && myMapAcc!=null){
for(Id accId : myMapAcc.keyset()){
for(integer i = 0; i<myMapAcc.get(accId);i++){
contact mycon = New Contact();
mycon.AccountId = accId;
mycon.FirstName = 'Trigger';
mycon.LastName = 'contact' +i;
lstContact.add(mycon);
}
}
}
if(lstContact.size() > 0 && lstContact != null){
insert lstContact;
//Database.insert(lstContact , false);
}
}

public class AccountTriggerHandler{
public static void AfterInsert(List<Account> lstAccount){
        contactCreationfromLocation(lstAccount);
    }
}


Trigger code:
--------------
trigger myAccountTrigger on Account (Before Insert,Before Update,Before Delete,After Insert,After Update,After Delete,After Undelete){
   
    //Define Context Variable to Call the Trigger Logic.
   
    if(Trigger.isAfter && Trigger.IsInsert){
        AccountTriggerHandler.AfterInsert(Trigger.New);
    }

}


Trigger Example Scenario:
==========================
When ever Opportunity "Stage" is Modified to "closed won" then Set "Closed Date" as
Todays Date & Type as a New Customer.

Object : Opportunity Object.
Event  : Before Update.

trigger myOpportunityTrigger on Opportunity (before insert,before update) {
    
    if(Trigger.Isbefore && Trigger.isUpdate){
        for(Opportunity myopp : Trigger.New){
            if(myopp.StageName == 'Closed Won'){
                myopp.CloseDate = system.today();
                myopp.Type = 'New Customer';
            }
        }
    }
}

Trigger Example:
-----------------
Write a Trigger in which if an Accout that has a Related contact and user tries to delete 
the account the it should throw an error "Account Canot Be deleted as it contain The Contact"

Object : Account.
Trigger event : Before Delete.

Post a Comment

Post a Comment (0)

Previous Post Next Post