I am looking to create a trigger that will update a lead status from "open" to contacted after the first task is completed. I tried this but it changed the lead status every time any task was completed.

trigger changeLeadStatus on Task (before insert, before update) {
    String desiredNewLeadStatus = 'Working - Contacted';

    List<Id> leadIds=new List<Id>();
    for(Task t:trigger.new){
            if(String.valueOf(t.whoId).startsWith('00Q')==TRUE){//check if the task is associated with a lead
            }//if 2
        }//if 1
    List<Lead> leadsToUpdate=[SELECT Id, Status FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
    For (Lead l:leadsToUpdate){

        update leadsToUpdate;
    }catch(DMLException e){
        system.debug('Leads were not all properly updated.  Error: '+e);

You need to check the old status of the lead before you set the new one. So change this line:

For (Lead l:leadsToUpdate){


For (Lead l:leadsToUpdate){
    if (l.Status == 'Open')

Also when you change the status, add the lead record into another separate list which you'll update later. You don't want to force update the records if there were no changes.

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.