This section applies your knowledge of Apex’s outbound email features to enhance the Services Manager sample application. Many scenarios in Services Manager could benefit from email notifications. For example, consultants have requested that they get an email when a timecard is approved or rejected by their project managers.
To implement this change, add a trigger on the after update
event of the Timecard object. If the new value of the Timecard’s Status
field is Approved
or Rejected
, query the Contact record that created the Timecard. Send an email notification of the change to the Contact.
Listing 5.41 is a sample implementation. It begins by checking to make sure that the updated Timecard contains a new value for the Status
field and that the new status is either Approved
or Rejected
. If so, it makes three queries to retrieve data to send the notification email: the email address of the Contact logging the Timecard, the name of the Project, and the name of the user modifying the Timecard record. It constructs the email message and sends it.
trigger handleTimecardNotifications
on Timecard__c (after update) {
for (Timecard__c timecard : trigger.new) {
if (timecard.Status__c !=
trigger.oldMap.get(timecard.Id).Status__c &&
(timecard.Status__c == 'Approved' ||
timecard.Status__c == 'Rejected')) {
Contact resource =
[ SELECT Email FROM Contact
WHERE Id = :timecard.Contact__c LIMIT 1 ];
Project__c project =
[ SELECT Name FROM Project__c
WHERE Id = :timecard.Project__c LIMIT 1 ];
User user = [ SELECT Name FROM User
WHERE Id = :timecard.LastModifiedById LIMIT 1 ];
Messaging.SingleEmailMessage mail = new
Messaging.SingleEmailMessage();
mail.toAddresses = new String[]
{ resource.Email };
mail.setSubject('Timecard for '
+ timecard.Week_Ending__c + ' on '
+ project.Name);
mail.setHtmlBody('Your timecard was changed to '
+ timecard.Status__c + ' status by '
+ user.Name);
Messaging.sendEmail(new Messaging.SingleEmailMessage[]
{ mail });
}
}
}
This implementation is not batch-safe. It makes four SOQL queries per Timecard. Even if this were addressed, the code could easily reach the limit of ten email invocations.
To fix this problem, you could change the code to use the MassEmailMessage
, building a list of recipient Contact objects from the batch. Unfortunately, the MassEmailMessage
’s whatIds
field cannot be used with custom objects, so you’ll have to forgo the customized message detailing the changes to the Timecard.
An alternative is to anticipate the governor limit. If a batch of Timecards requires more than ten email notifications, send the ten and suppress subsequent notifications.
18.222.111.134