function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Suhas GB 4Suhas GB 4 

When to use before insert, before update, after insert and after update in Triggers ? I would like to know in which scenario what to use, since I'm getting confused to use them. Please explain it with an example, so there could be clarity on these.

JLA.ovhJLA.ovh
To make it simple:
  • use "before" triggers to validate data or update fields on the same record being triggered.
  • use "after" triggers to update parent or related records
  • use "insert" for events that occur on record creation
  • use "update" for events on existing records
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Suhas,
  • Before triggers:  used to update or validate record values before they’re saved to the database.
  • After triggers: used to access field values that are set by the system (such as a record's Id or LastModifiedDate field) and to effect changes in other records. The records that fire the after trigger are read-only.
  • We cannot use After trigger if we want to update a record because it causes read only error. This is because after inserting or updating, we cannot update a record.

Please check the below link for an understanding of Triggers.
  • Please check the Trailhead module on the trigger so that you can accelerate on trigger concepts one of the best ways to learn the Salesforce.Please check the link below.
I hope it will be helpful.

Please mark it as best answer if it resolved the issue.

BestRegards
RahulKumar
Shiva RajendranShiva Rajendran
Hi AdminBooster,

Before vs After 
Basically before triggers are executed before the data is commited to the database .
You can change the field value in before trigger and need not commit it, salesforce will automatically commit it
You can validate the record and make a record not available to save in before trigger
Fields like Id are not accessible in this trigger.


After Trigger:

After trigger works after the data is commited to the database
Fields like Id are accessible in this trigger.
If changes are made in this trigger , You should manually commit this to the database


Insert and Update :

Insert works when a record is inserted while update works when a record is updated .
Upsert will call both the update and insert trigger

Thanks and Regards,
Shiva RV
Amit Chaudhary 8Amit Chaudhary 8
Please check below post for same
1) http://www.sfdc99.com/2014/01/25/use-vs-triggers/
2) https://hisrinu.wordpress.com/2011/05/17/difference-between-before-trigger-and-after-trigger/
3) http://salesforce.stackexchange.com/questions/2033/how-should-i-determine-whether-to-use-before-or-after-when-writing-a-trigger


BEFORE trigger
  1. BEFORE triggers are usually used when validation needs to take place before accepting the change. They run before any change is made to the database.
  2. In case of validation check in the same object.
  3. Insert or update the same object.
An example. If user leaves the opportunity probability field blank, you may want to default it to 10%.
trigger setProbabilityDefaultOnOpportunities on Opportunity (before insert, before update) {
     for (Opportunity opp : trigger.new) {
         if opp.probability = NULL {
            opp.Probability = 10;
         }
     }
}


AFTER trigger
  1. AFTER triggers are usually used when information needs to be updated in a separate table due to a change.
  2. They run after changes have been made to the database (not necessarily committed).
  3. Insert/Update related object, not the same object.
  4. Notification email.
  5. We cannot use After trigger, if we want to update a record because it causes read only error. This is because after inserting or updating, we cannot update a record.
An example, you may want to create a task for every newly created opportunity if the stage is over 50%. Or, you may want to send emails to the manager of the opportunity owner if the stage is over 70%, etc.
trigger createNewTasksForOpportunities on Opportunity (after insert) {
        List newTasks = new List<Task>();
        for (Opportunity opp : trigger.new) {
            newTasks.add (aTask = new Task (Subject = ‘Follow up on the new opportunity’, WhoId = opp.Owner.Id, ….);
        }
        if (newTasks.isEmpty() == False) {
           Database.update(newTasks);
        }
}


Let us know if this will help you

 
Srinivas TestingSrinivas Testing
@Amit Chaudhary 8 

I tried your first sample trigger, its throwing error
2nd trigger is giving this error: Error: Compile Error: Invalid identifier '‘Follow'. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 8 column 55

As a beginner I am getting worried about errors 
 
Amit Chaudhary 8Amit Chaudhary 8
Update code like below
trigger setProbabilityDefaultOnOpportunities on Opportunity (before insert, before update) {
     for (Opportunity opp : trigger.new) {
         if (opp.probability == NULL ){
            opp.Probability = 10;
         }
     }
}

 
david willy 1david willy 1
Great. This is such awesome content I got to read after a lot of time. Its so interesting as well as informative.I am sure everyone who read it got a lot to learn from it. www.dumpsexpert.com/NCP-5-10-Exam-Dumps.html