function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Edward Scott 5Edward Scott 5 

Update lead Status

Hi,

I am working on a trigger to update the lead status from "Not Contacted/New" to "Contacted once a task has been marked complete. The trigger is working fine on the Lead but is throwing an exception when the record is a Contact. It works fine if I am just adding a task manually but if I use Salesforce for outlook to log an email I get an error message back that says "(Undelivered): 554 The apex class Messaging.EmailToSalesforceHandler failed due to: System.UnexpectedException: common.exception.ApiException: updateLeadStatus: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.updateLeadStatus: line 6, column 1"

Below is the trigger itself. I was wondering if anyone could give me some suggestions on how to fix it.

Thanks,

Edward

trigger updateLeadStatus on Task(after insert, after update){
    
    Set<Id> leadIds = new Set<Id>();
    
    for(Task tsk : trigger.new){
        if(String.valueOf(tsk.WhoId).startsWith('00Q') && tsk.type != 'Other' && tsk.status == 'Completed'){
            leadIds.add(tsk.WhoId);
        }
    }
    
    List<Lead> updateLeadList = new List<Lead>();
    for(Lead ld : [Select status from Lead where Id in :leadIds]){
        if (ld.status == 'Not Contacted/New'){
        ld.status = 'Contacted'; //Use any other value as per your requirement
        updateLeadList.add(ld);
        }
    }
    
    if(updateLeadList.size() > 0){
        update updateLeadList;
    }
}
AshlekhAshlekh
Hi,

Just Update the code.
trigger updateLeadStatus on Task(after insert, after update){
    
    Set<Id> leadIds = new Set<Id>();
    
    for(Task tsk : trigger.new){
        if(tsk.WhoId != null && String.valueOf(tsk.WhoId).startsWith('00Q') && 
                tsk.type != 'Other' && tsk.status == 'Completed')
         {
            leadIds.add(tsk.WhoId);
        }
    }
    
    List<Lead> updateLeadList = new List<Lead>();
    for(Lead ld : [Select status from Lead where Id in :leadIds]){
        if (ld.status == 'Not Contacted/New'){
        ld.status = 'Contacted'; //Use any other value as per your requirement
        updateLeadList.add(ld);
        }
    }
    
    if(updateLeadList.size() > 0){
        update updateLeadList;
    }
}
-Thanks
Ashlekh Gera