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
Amber WanAmber Wan 

How to trigger the email notification to the task owner for the task update by Apex Coding?

Hi,
I'd like to set up the email notification for the task update. Once the Comments or Status field in the existing task has been updated by someone else, it can trigger the email notification to send to the task owner. Can it be done by the Apex Coding? 
SlashApex (Luis Luciani)SlashApex (Luis Luciani)
Hi Amber,

Yes, you can absolutely accomplish this with an apex trigger, HOWEVER, I would recommend using a Workflow. It will be a lot easier to implement and maintain.

Goog luck!
Amber WanAmber Wan
Hi Luis,
Thanks for your reply. I have tried to create a workflow and added the action as the email alert to get it done, but there is no option for the Task in the object selection list under the Email Alert.
 
ra1ra1
Workflow based Email Alert is not avaiable for Task or Event  (IDEA (https://success.salesforce.com/ideaview?id=08730000000BpAuAAK) is already posted with good vote count).

You can use trigger to notify user using Trigger, below is sample code
trigger NotifyTaskOwner on Task (After Update) {

    List<Id> taskIdList;    
    Map<Id, List<Id>> ownerIdTaskIdMap = new Map<Id, List<Id>>();

    Task oldTask;
    for(Task newTask : Trigger.new){
        oldTask = Trigger.oldMap.get(newTask.id);
        
        if(newTask.status != oldtask.status  || newTask.Description != oldTask.Description) {
            taskIdList = ownerIdTaskIdMap.get(newTask.ownerId);
            
            if(taskIdList == null) {
                taskIdList = new List<Id>();
            }
            
            taskIdList.add(newTask.Id);
            ownerIdTaskIdMap.put(newTask.ownerId, taskIdList);
        }
    }
    
    if(!ownerIdTaskIdMap.isEmpty()) {
		Map<Id, User> userMap = new Map<Id, user>([select id, email from user where id in: ownerIdTaskIdMap.keySet()]);
        
        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

        String userEmail, emailBody;
        String emailSubject = 'Task updated'; // define your own subject
        
        //loop
        for(Id ownerId : ownerIdtaskIdMap.keySet()){
			userEmail = userMap.get(ownerId).Email;
            taskIdList = ownerIdtaskIdMap.get(ownerId);
            emailBody = 'Email body ' + taskIdList;
            
            for(Id tskId : taskIdList){
                // compose your email body content
            }
            
            Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();	//initiallize messaging method
            singleMail.setToAddresses(new String[] {userEmail}); 
            singleMail.setSubject(emailSubject); 
			singleMail.setPlainTextBody(emailBody); 
	        emails.add(singleMail);	//add mail
        }

        //send mail
        Messaging.sendEmail(emails);
    }
}

Please update Email subject & body content as per ur need.

Thanks
SlashApex (Luis Luciani)SlashApex (Luis Luciani)
Hi Amber,

You are correct. Sorry about that.

Let me make it up to you, here is a trigger that might work for you.
 
trigger trgTask_EmailOwnerOnComplete on Task (after update)
{
    //Query for email template to use
    EmailTemplate template = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'ENTER Email Template API NAME HERE'];
    
    //Determine which tasks have been just completed by someone besides the task Owner and create email message
    List<Messaging.SingleEmailMessage> mailsToSend = new List<Messaging.SingleEmailMessage>();
	for(Task t : trigger.new)
    {
        if(t.Status == 'Completed' && t.Status != trigger.oldMap.get(t.id).Status && t.OwnerId != UserInfo.getUserId())
        {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTargetObjectId(t.OwnerId);
            mail.setWhatId(t.Id);
            mail.setTemplateId(template.Id);
            
            mailsToSend.add(mail);
        }
    }
    
    //Send Email
    if(mailsToSend.size() > 0)
    {
		Messaging.sendEmail(mailsToSend);        
    }
}

 
Amber WanAmber Wan
Thank you Luis for the codes. I am new to it. I can see the Apex Triggers under the Develop but I don't know how to add your codes to our system. Do you have any instructions? Thanks a lot!! 
sreenivasAppssreenivasApps
Hi Amber,

Two ways you can add
1) Eclipse - create new trigger
2) go to Customize --> Activities --> triggers -- click on New  
3) Open Developer console - you will find File, Edit, debug
      Select File --> New --> apexTrigger
      give the trigger name and select the task__c as sObjectType
Amber WanAmber Wan
Hi app cs,

1) I cannot find this path in our current system.
2) There is no New option for me to add the trigger.
3) The only sObjectType in the list is "Task". I typed the name and selected "Task" and got the error "Can not create Apex Trigger on an active organization".

Please help. Thanks.
Amber WanAmber Wan
Hi Luis Luciani,

I copied the codes you made for me to the Sandbox and tried to update the comments field of the exisitng task. Then I got the error message as follows:

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger trgTask_EmailOwnerOnComplete caused an unexpected exception, contact your administrator: trgTask_EmailOwnerOnComplete: execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.trgTask_EmailOwnerOnComplete: line 4, column 1


Can you help to take a look into it?

Thanks,
Amber
SlashApex (Luis Luciani)SlashApex (Luis Luciani)
Hi Amber,

Please make sure that you replace the "ENTER Email Template API NAME HERE" with the name of the email template that you would like to use. If you dont have one, create the template and then set the name on the code.
Amber WanAmber Wan
Hi Luis,

I have changed the statement to replace the email tamplate
EmailTemplate template = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'TaskUpdate'];

When I tried to change the status to the Completed, I got another error message:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger trgTask_EmailOwnerOnComplete caused an unexpected exception, contact your administrator: trgTask_EmailOwnerOnComplete: execution of AfterUpdate caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.: []: Trigger.trgTask_EmailOwnerOnComplete: line 24, column 1


Another question, can you also include the update of the Comments in the triggers?

Thank you,
Amber
Shannon Andreas 21Shannon Andreas 21
Anyone have a test class for this trigger?

Thanks!!

Shannon
Stacy Jewell 2Stacy Jewell 2
Hi SlashApex (Luis Luciani)- I tried using your trigger information, but I'm getting this warning: Error: Compile Error: Extra '{', at '02'. at line 2 column 1. When I remove the '{', I get this message, Error: Compile Error: Missing '{' at '02' at line 2 column 1. Do you have any advice?

Thanks!
Stacy
Tara RootTara Root
Hello! Working with our professional essay writing services https://topessaybrands.com/review/varsitytutors/ could not be any easier. We provide you with a quick and easy to use system through which you can be guaranteed of the top essay that you are looking for. Simply follow the process that we detail here and you will soon be working with the best essay writers online