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
shalini sharma 24shalini sharma 24 

before update vs after update trigger

Hi ,

I have a scenario where i want to update the lead record's rating field when the status changes to status == 'Closed - Not Converted'.And i wrote after update trigger  for this: Below is the code
 trigger leadUpdate on Lead (after update) {
list<lead> leadUpdate = new List<Lead>();
    for(Lead l :trigger.new){
        if(trigger.oldMap.get(l.id).status != l.status && l.status == 'Closed - Not Converted'){
           lead ld = new lead(id = l.id,rating = 'cold');
            leadUpdate.add(ld); 
        }
    
    }
    update leadUpdate; 
}


And samething can be achieved through  before trigger as well. Below code:
trigger  leadUpdate on Lead (before update) {
List<lead> leadUpdate = new List<Lead>();
if(trigger.isBefore && trigger.isUpdate){
         for(Lead l :trigger.new){
        if(trigger.oldMap.get(l.id).status != l.status && l.status == 'Closed - Not Converted'){
           l.rating = 'cold';
            leadUpdate.add(l); 
        }
    
    }
   
    
    }
}
 
v varaprasadv varaprasad
Hi Shalini,

As per the best practices if we want to update on the same record we need to use Before events only.
If we use after update here DML events count will happen.so governor limits will be reduced.

lead ld = new lead(id = l.id,rating = 'cold');
here we are adding again leadid and again we are updating samereocrd.This is not best a best practices.
 

Trigger events best practices : 

Use Before Trigger:
In the case of validation check in the same object.
Insert or update the same object.

Use After Trigger:
Insert/Update related object, not the same object.
Notification email.
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.


So in the above triggers, you need to use before update only.

Hope it helps you.


Thanks
Varaprasad


 
Sunil Shah 12Sunil Shah 12
Thank you Mr Varaparsad :)
Asad WaliAsad Wali

Hi

Is it possible if we change address then it will update our custom field with REST API ?