You need to sign in to do that
Don't have an account?
shalini 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);
}
}
}
}
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);
}
}
}
}
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
Hi
Is it possible if we change address then it will update our custom field with REST API ?