0

I am trying to identify the last (most recently created) email related to a specific case. My purpose is run queries on cases and then for related emails and only show the last created email related to that case.

I have added a checkbox (boolean) field to the Email Message object to track this and thought a trigger would be an efficient way to accomplish this after inserts and updates. However, my trigger does not update the last email related to the case. My assumption is I am using Trigger.new in the wrong context.

If there are most efficient ways to accomplish this other than a trigger, I am open to suggestions.

Trigger:

trigger identifyLastEmailMessage on EmailMessage (after insert, after update) {
    List<EmailMessage> emailThatStartedTrigger = new List<EmailMessage>(); 
    emailThatStartedTrigger = Trigger.new; 
    system.debug('Case Id: ' + emailThatStartedTrigger[0].ParentId);
    List<EmailMessage> allEmailsRelatedToThisCase = new List<EmailMessage>(); 
    allEmailsRelatedToThisCase = [select Id, Last_Email_for_Case__c, CreatedDate from EmailMessage where ParentId = :emailThatStartedTrigger[0].ParentId ORDER BY CreatedDate ASC];

    if (Trigger.isAfter) {

        for (integer i =0; i< allEmailsRelatedToThisCase.size(); i++) {
            if (i == 0) {
                allEmailsRelatedToThisCase[i].Last_Email_for_Case__c = true; 
            }
            else {
                allEmailsRelatedToThisCase[i].Last_Email_for_Case__c = false; 
            }

        }

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.