0

So I am running a before insert trigger on the EmailMessage object and after debugging the email, I found that the fields are null. ParentId in particular as that is what I am using for the logic. However, checking Salesforce after the fact, the fields seem to be populated.

trigger EmailMessage on EmailMessage (before insert) {

    List<Id> parentIdList = new List<Id>();

    for(EmailMessage email: Trigger.New){
        System.debug(email);
        parentIdList.add(email.ParentId);
      }

    List<Case> listOfCases = [SELECT Id, AccountId FROM Case WHERE Id in :parentIdList];
    for(EmailMessage email: Trigger.new){
        for(Case c: listOfCases){
            if(email.ParentId == c.Id){
                email.Company__c = c.AccountId;
            }
        }
    }

}

The debug for email:

12:38:44:181 USER_DEBUG [7]|DEBUG|EmailMessage:{Id=null, ParentId=null, ActivityId=null, CreatedById=null, CreatedDate=null, LastModifiedDate=null, LastModifiedById=null, SystemModstamp=null, TextBody=ddddd, HtmlBody=<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40">

Any ideas on what is causing this? Thanks for any guidance.

1
  • what is the context where you are testing this? (1) In email-to-case ? (2) in some testmethod ? (3) anonymous apex?
    – cropredy
    Commented May 23, 2020 at 22:06

1 Answer 1

0

Trigger.new doesn't house any id before insert. Since the record has not been created yet. Change it to after insert and when any new Email is created you can see the fields you added while creating.

trigger EmailMessageHandler on EmailMessage(after insert){
    for(EmailMessage email : trigger.new){
      System.debug(email);
     }
} 
1
  • Doing that way gives me a : System.NullPointerException: Attempt to de-reference a null object error. Documentation says an after insert with trigger.old = null.
    – fynmnx
    Commented May 21, 2020 at 17:19

You must log in to answer this question.

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