0

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

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

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

For (Lead l:leadsToUpdate){
    l.Status=desiredNewLeadStatus;

to

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

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.