Friday, October 2, 2020

Apex Triggers

->Apex Triggers are blocks of Apex code that are executed under certain conditions

->Just like a Workflow Rule,or a Process,an Apex Trigger is tied to 1 Object and it waits for an event to happen before it executes its code.

 

->For example, the events are like before record insertion, after record update,after record deletion.....etc.

->Triggers can be defined for top-level standard objects, such as Account or contact, custom objects, and some standard child objects

 

 

->Triggers are active by default when created - no need to Active them.

 

Where to Write Apex Triggers:-

------------------------------

->from any IDE like the force.com IDE on Eclipse, and the Developer console.

->from the Setup Menu.

 

 

When to use Apex Triggers:-

---------------------------

->Use triggers to perform tasks that can't be done by using the point-and-click tools in the Salesforce user interface.

->If we are requirement can't be done through workflow Rules,Process builders,Approval Process,Flows...etc.

 

Apex Trigger Syntax:-

---------------------

->The syntax of a trigger definition is different from a class definition's syntax.

->A trigger definition starts with the trigger keyword.It is then followed by the name of the trigger, the on keyword,

            the salesforce object that the trigger is associated with, and finally the conditions under which it fires.

->A trigger example has the following syntax.

 

syntax:

--------

trigger <TriggerName> on <ObjectName> (<Trigger Event(s)>){

 

//trigger code

 

}

 

trigger Opportunity Trigger on Opportunity (before insert){

 

//trigger code

 

}

 

Trigger Event:-

---------------

->The Trigger event specifies under which circumstance this Trigger will run

->You can have 1 or more events on each Trigger definition in a  comma-separated list. The events can be

 

->before insert,before update,before delete,after insert,after update,after delete,after undelete.

 

 

used when:

 

Change the same Object

Validate the same Object

 

 

 

Trigger Context variables:-

---------------------------

-> Trigger can fire when one record is inserted, or when many records are inserted in bulk via the API or Apex.

-> To access the record(s) that caused the trigger to fire, Salesforce has many Trigger Context Variables

->for example:-

---------------

->Trigger.New contains the List of all the records that were inserted in insert or update triggers

->Trigger.Old provides the old version of records before they were updated in update triggers, or a list of deleted records in delete triggers.

 

 

Trigger Explanation:-

 

->trigger HelloWorldTrigger on Account(before insert){                                                        

Trigger on 1 record only,that adds a statement to the Debug Log before inserting an Account record.Test it by Inserting an account record.

            System.debug("Hello World");

}

 

->trigger HelloWorldTrigger on Account(before insert){                                                                                                                                                         Trigger that uses the context Variable Trigger.New to add a Description to each Account before being insert

 

            for(Account a:Trigger.New){

                        a.Description = "New Description";

            }

}

 

->trigger TaskTrigger on Account(after insert){                                                                                  Trigger that adds a new Task after inserting an Account record.

for(Account a:Trigger.New){

 

The Task is related to the Account inserted,and the ID of the Account is needed when creating the new Task.

                                                                                                                                                                                                                                                                                                                        that's why we are using after insert event.                     

                        Task task = new Task();                                                                                                                                                                                                                                

                        task.ownerId = a.ownerId;

                        task.subject = 'New Account Task';

                        task.whatId = a.Id;

                        task.priority = 'Normal';

                        insert task;

            }

}

->trigger ContextExampleTrigger on Account (before insert,after insert,after delete){                                                         Trigger that uses multiple events,and acts differently based on the event by using if-else statements

 

            if(Trigger.isInsert){

                        if(Trigger.isBefore){

                                    //process before insert

                        }

                        else if(Trigger.isAfter){

                                    //process after insert

                        }

            }

            else if(Trigger.isDelete){

                        //process after delete

            }

}          

 

Using SOQL in Apex Triggers

---------------------------

AS we learned earlier,SOQL can return

            ->single concrete sObject

            ->List of concrete sObjects

            ->Integer

            ->single AggregateResult

            ->List<AggregateResult>

            ->you can run SOQL in your Apex Classes and Triggers to retrive any record

            ->SOQL code should be enclosed between []

           

SOQL Variable Binding:-

-----------------------

-> you can bind variables from Apex code,or execute Apex from your Apex code into a SOQL query that you are writing in the Apex class/Trigger.

-> But for the variable to work, Make sure that you precede the variable with ':' for example

 

String strName = "Lokesh J"

List<Position__c> positionList = [SELECT Name from Position__c where Name = :strName];

 

Using Trigger Exceptions

------------------------

->Trigger Exceptions are used to add restrictions on certain database operations, for example preventing saving a record when a condition is met

->To prevent saving records in a trigger, call the addError() method on the sObject in question

->The addError() method throws a fatal error inside a trigger, and prevents DML statement from completing

->The error message is specified by the coder, is displayed in the user interface and is logged

->Example: prevent deletion of an Account if it has at least 1 related opportunity, and display an error message on the page.

 

Using Trigger exceptions:

-------------------------

->trigger AccountDeletion on Account (before delete){

            List<Account> accWithOpp = [SELECT Id,Name from Account WHERE ID IN (SELECT AccountID from opportunity) AND ID IN :trigger .old];

            for(Account ac: trigger.old)

            {

                        ac.addError('Can't delete account with related opportunities');

            }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3 comments:


  1. Thanks for helping us understand this topic. you have written it in a way that makes it
    very simple to understand. Thanks you so much.

    click here

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks for sharing this blog this content is very significant for me I really appreciate you.
    The blogs you have posted have taught you a lot of good things Thanks for posting.
    click here now

    ReplyDelete