+ Start a Discussion

A Vexing Problem: after insert trigger on task cannot yet see its EmailMessage

Our application uses an 'after insert' task trigger to trap the "Log a Call" and "Send an Email" actions.  We use this to log the first response on a Case.  This much works like a charm.

However, when Email To Case processes an inbound email, it creates a task.  We obviously don't want to count these as "responses" for that Case.  Luckily, E2C also inserts an EmailMessage object, and every EmailMessage object has a flag called "Incoming" plus a lookup field called ActivityId which together could be used to filter out the incoming emails.

Not so luckily, the EmailMessage objects don't get inserted until after the 'after insert' Task trigger has run.  So, the result is that our trigger has to make its decision about whether a "response" has occurred before the data it needs is actually available.  Specifically, the code below never prints anything in after insert:

for(Task t : trigger.new) {
EmailMessage[] emArr = [select Id,Incoming from EmailMessage Where ActivityId=:t.Id];
for(EmailMessasge email : emArr){
system.debug( 'email was:' + (email.Incoming ? 'incoming' : 'outgoing') );

b/c the inner loop never runs.  Does anyonre have a good suggestion (other than button overrides) to distinguish between outbound emails and inbound ones at the point where we are executing?

UPDATE 9/3/08:  Clarified wording + fixed the ternary operator in the code snippet.

Message Edited by MikeGoelzer on 09-03-2008 09:55 PM