2

I have a Service Cloud in which:

  • a User A owns a Case X;
  • a User B receives a call about the Case X;
  • the User B creates a task of type "urge" on the Case X and sets it as "completed" (the User A is not notified about it);
  • what I want: an email should be automatically sent to the case owner (User A) alerting him about the "urge" received.

I tried to create a workflow but.... for the task object the option Email Alert is not available (for the other objects it is!).

Trigger:

trigger SollecitoToMail on Task (after insert, after update) {
//Map<Id, Case> mappa = new Map<Id,Case>();


for(Task t: Trigger.new){


    if(t.subject=='sollecito' && t.status=='Completata'){
        System.debug('Devi mandare la mail');

        //send email to the Case owner
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //String[] toAddresses = new String[] {address};

    // I choose the EmailTemplate
        EmailTemplate et = [SELECT Id FROM EmailTemplate Where Name = 'Sollecito' LIMIT 1];
        mail.setTemplateId(et.Id);

    // I have to choose the address. It has to be the address of the Case Owner (the Case related to the Task ==> t.WhatId)


        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                             new Messaging.SingleEmailMessage[] { mail });

    } 

}

}

Concept: I should create a map of Id and Case, save the case related to the task, and then take the mail of the Case owner.

How can I modify the code to implement that?

2

1 Answer 1

1

A better solution for this is to:

  1. Have your Task trigger update a field on Case (Urgent_Task_Completed__c) if the Task Owner is not the Case Owner
  2. Use a workflow on Case that looks to see if Urgent_Task_Completed__c = true
  3. Workflow sends email to Case owner and then does field update to set Urgent_Task_Completed__c to false

Your existing trigger has a couple of issues:

  1. It does a select of emailTemplate within a for loop - will have governor issues with bulk operations
  2. It calls Messaging.sendEmail in a for loop - you are limited in the number of apex outbound messages you can do per day - and hence should try and use OOB workflow/process builder email alerts whenever possible as they have much larger limits

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .