+ Start a Discussion
Jon RodigerJon Rodiger 

Need help updating lead status from task trigger

I am finishing up my code and the last problem I haven't been able to solve is: when the final task for a lead is completed, I want the lead status to be updated. I have the task whoId field value, but I don't know how to use this value to access and update the lead that the task is related to. This is my code so far:
trigger Scheduler on Task (after insert, after update) {
    // Iterate through all tasks
    for(Task t : Trigger.new){
        // Schedule follow up task for completed tasks depending on task subjecct
        if(t.Status == 'Completed'){    
            if(t.Subject == 'Send Initial Email'){
                Task newTask = new Task(Subject = 'Make Initial Phone Call', IsReminderSet = True, ReminderDateTime = System.now()+1, Activitydate = System.now().date().addDays(1), WhoId = t.WhoId, ownerId = t.ownerId);
                insert newTask;
            } else if(t.Subject == 'Make Initial Phone Call'){
                Task newTask = new Task(Subject = 'Send Email #2', IsReminderSet = True, ReminderDateTime = System.now(), Activitydate = System.now().date(), WhoId = t.WhoId, ownerId = t.ownerId);
                insert newTask;
            } else if(t.Subject == 'Send Email #2'){
                Task newTask = new Task(Subject = 'Make Phone Call #2', IsReminderSet = True, ReminderDateTime = System.now(), Activitydate = System.now().date().addDays(1), WhoId = t.WhoId, ownerId = t.ownerId);
                insert newTask;
            } else if(t.Subject == 'Make Phone Call #2'){
                Task newTask = new Task(Subject = 'Send Email #3', IsReminderSet = True, ReminderDateTime = System.now(), Activitydate = System.now().date(), WhoId = t.WhoId, ownerId = t.ownerId);
                insert newTask;
            } else if(t.Subject == 'Send Email #3'){
                Task newTask = new Task(Subject = 'Make Phone Call #3', IsReminderSet = True, ReminderDateTime = System.now(), Activitydate = System.now().date().addDays(1), WhoId = t.WhoId, ownerId = t.ownerId);
                insert newTask;
            // When final task is completed, change lead status to 'unresponsive'
            } else if(t.Subject == 'Make Phone Call #3'){
                
                Lead myLead = [SELECT Id, Status FROM Lead WHERE Id = :t.whoId];       
                
                myLead.Status = 'Unresponsive';
                
                update myLead;
            }
        }    
    }
}

Any help would be greatly appreciated. Thank you!
Best Answer chosen by Jon Rodiger
VineetKumarVineetKumar
Your code looks correct. No need for query on line 24, it would be like below as well.
if(t.whoId != null){				
	Lead myLead = new Lead(Id = t.whoId);
	myLead.Status = 'Unresponsive';
	update myLead;
}
Let me know if you are encountering any error