2

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 same thing 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 want to ask which one is the correct approach and what is the difference?

3

For your scenario before update makes more sense as you are not updating any other related record and in before update scenario you don't have to explicitly write update statement.

Also if we update the same object that's in trigger context you can easily run into recursions or entity is locked error .

Use after update if you are updating related records and not records that are in trigger context.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.