+ Start a Discussion
Chinnu ChinnuChinnu Chinnu 

Write a trigger that automatically sets Tasks to the “Completed” status whenever their associated Leads are set to any Closed status. Make sure your trigger is bulkified - there should be no SOQL queries inside any loops!

Send an email to all Lead owners notifying them that their Tasks have been automatically completed. This should be bulkified too!
Best Answer chosen by Chinnu Chinnu
Khan AnasKhan Anas (Salesforce Developers) 
Hi Gowtham,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger LeadTaskTrigger on Lead (after update) {
    
    Set<Id> leadIds = new Set<Id>();
    
    for(Lead ld : Trigger.new){
        if(ld.Status == 'Closed - Converted'){
            leadIds.add(ld.Id);
        }
    }
    
    List<Task> leadTasks = [Select Id, Status from Task where WhoId in :leadIds];
    
    for(Task t : leadTasks){
        t.Status = 'Completed';
    }
    
    if(leadTasks.size()>0){
        UPDATE leadTasks;
        
        EmailTemplate et = [SELECT Id FROM EmailTemplate WHERE developername = 'Your_Template_Name' LIMIT 1];
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        
        for(Lead ld : Trigger.new){
            if(ld.Status == 'Closed - Converted'){
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setTargetObjectId(ld.Id);
                //singleMail.setPlainTextBody('Task has been automatically completed');
                singleMail.setTemplateId(et.Id);
                singleMail.setSaveAsActivity(false);
                emails.add(singleMail); 
            }
        }
        Messaging.sendEmail(emails);
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas