Tuesday 1 September 2015

Understanding Apex Triggers


Trigger Events :

 Events are the database activities which fires a trigger, this again is required for a trigger. So by this we can say Trigger is Apex Code that gets executed before and after of these operations.

  • Insert : Before and After
  • Update : Before and After
  • Delete : Before and After
  • Merge : Not directly, but both insert and delete trigger get fired for winning and losing records.
  • Upsert : Not directly, but both insert and update trigger gets fired
  • Undelete : After

Trigger Events :  Before Insert , After Insert , Before Update , After Update

Trigger Context Variables :

Trigger.New
Trigger.Old
Trigger.NewMap
Trigger.OldMap
Trigger.isinsert
Trigger.Isupdate
Trigger.isDelete
Trigger.isbefore
Trigger.isafter

Variable
Description

 isInsert

Returns true if this trigger was fired due to an insert operation, from the Salesforce user
interface, Apex, or the API.

 isUpdate 


Returns true if this trigger was fired due to an update operation, from the Salesforce user
interface, Apex, or the API.

 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

Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is,
after an undelete operation from the Salesforce user interface, Apex, or the API.)



Structure trigger like this :

Writing single trigger on a object is preferable always . Please make sure your using the trigger events conditions and manage your code well .

trigger Test_Trigger on Account ( after update , after insert , before insert ,
before update , after delete , before delete )
    {
   
        if (Trigger.isBefore)
            {
           
                if (Trigger.isInsert)
                    {
                        // Logic to be executed for Before Insert
                    }
               
                if (Trigger.isupdate)
                    {
                        // Logic to be executed for Before Update
                    }
             
                 if (Trigger.isDelete)
                    {
                        // Logic to be executed for Before Delete
                    }
            }
       
        if (Trigger.isAfter)
            {
       
                if (Trigger.isInsert)
                    {
                        // Logic to be executed for After Insert
                    }
               
                if (Trigger.isupdate)
                    {
                        // Logic to be executed for After Update
                    }
           
                 if (Trigger.isDelete)
                    {
                        // Logic to be executed for After Delete
                    }
            }
        }

Thank you