You need to sign in to do that
Don't have an account?

Trigger on Lead Status change to alter Lead Owner?
I know how to write a trigger for Lead Conversion, but what about a trigger to change the lead owner to the current user when Lead Status field is altered to a specific value?
The basic goal here is I have a workflow that creates tasks for the Lead Owner when the status of a lead is altered to "qualified". However, the Lead Owner is not always the Current User who performed the status change. So I need to alter the Lead Owner to the Current User prior to the status change so that the task is created for the Current User/New Lead Owner.
Any guidance would be greatly appreciated, and thank you in advance.
Not quite. You don't need to do the SOQL query since you're in a before trigger and you won't want to do an update from there either. The record is already in memory. So change it to something like this:
trigger LeadUpdate on Lead (before update) { // no bulk processing; will only run from the UI if (Trigger.new.size() == 1) { // if a Lead has been updated to Qualified if (Trigger.new[0].Status == 'Qualified') { // Change Trigger.old[0].OwnerId to Current User ID Trigger.new[0].OwnerId = UserInfo.getUserId(); } } }
All Answers
UserInfo.getUserId();
returns the id of the currently running user.
Does this look right?
trigger LeadUpdate on Lead (before update) { // no bulk processing; will only run from the UI if (Trigger.new.size() == 1) { // if a Lead has been updated to Qualified if (Trigger.new[0].Status == 'Qualified') { // Change Trigger.old[0].OwnerId to Current User ID Lead l = [SELECT id, OwnerId FROM Lead WHERE id =: Trigger.old[0].Id]; l.OwnerId = UserInfo.getUserId(); update l; } } }
That code saves but I get an error when I try and save a lead with Status of Qualified:
"Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger LeadUpdate caused an unexpected exception, contact your administrator: LeadUpdate: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 00Q4000000PRH7JEAX; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 00Q4000000PRH7J) is currently in trigger LeadUpdate, therefore it cannot recursively update itself: []: Trigger.LeadUpdate: line 19, column 13"
Not quite. You don't need to do the SOQL query since you're in a before trigger and you won't want to do an update from there either. The record is already in memory. So change it to something like this:
trigger LeadUpdate on Lead (before update) { // no bulk processing; will only run from the UI if (Trigger.new.size() == 1) { // if a Lead has been updated to Qualified if (Trigger.new[0].Status == 'Qualified') { // Change Trigger.old[0].OwnerId to Current User ID Trigger.new[0].OwnerId = UserInfo.getUserId(); } } }