0

I have the below trigger on Case, which helps in copying the incoming EmailMessage to a custom field (of type Rich Text), so we can have an 'HTML' Case Description, rather then the out-of-the-box text converted field.

trigger updateCaseDescription on Case (before update) {
    set<Id> parentIds = new set<Id>();
    map<Id,EmailMessage> mapEmailMessage = new map<Id,EmailMessage>();
    for(Case c:trigger.new){   
        parentIds.add(c.Id);
    }   
    list<EmailMessage> lste = [select id,HtmlBody,parentId from EmailMessage where parentid in:parentIds and Incoming = true];

    if(lste.size() > 0 ){
     for(EmailMessage e:lste){
         mapEmailMessage.put(e.parentId,e);
     }
     list<Case> lstC = new list<Case>();
     for(Case c:trigger.new){ 
      if(mapEmailMessage != null && mapEmailMessage.get(c.Id) != null)   
          c.Description_HTML__c = mapEmailMessage.get(c.Id).HtmlBody;       
     }
    }
}

The trigger is actually setting the 'Description_HTML__c' custom field on EVERY incoming EmailMessage, which is not as desired. How can I limit this to perform only once - for the first Incoming EmailMessage?

Thank you.

  • 1
    You do realize mapEmailMessage cannot be null... – Adrian Larson Feb 9 '17 at 20:50
1

You could add another condition to your If statement...

if(mapEmailMessage != null && mapEmailMessage.get(c.Id) != null && parentIds.get(c.Id) == null)   {
      c.Description_HTML__c = mapEmailMessage.get(c.Id).HtmlBody;       
 }

That will inhibit any overwrites of that field from a new E-Mail. But, you will also have to change your set to a map..

map<Id, string> parentIds = new map<Id, string>();
map<Id,EmailMessage> mapEmailMessage = new map<Id,EmailMessage>();
for(Case c:trigger.new){   
    parentIds.put(c.Id, c.Description_HTML__c);
}
|improve this answer|||||
  • Thanks John. I added the condition as suggested, and after testing it seems to be working as expected. I then noticed your edited comment, and I wonder if this will still work without changing the 'set' to 'map'. – iDog Feb 9 '17 at 21:20
1

At the time of preparing mapEmailMessage map you can verify if parent Id already exists in the map or not. If not exists then only add the parent Id and corresponding EmailMessage.

for(EmailMessage e:lste){
    if(!mapEmailMessage.containsKey(e.parentId))
    {
       mapEmailMessage.put(e.parentId,e);
    }
}

Also, put suitable ORDER BY in SOQL

SELECT id,HtmlBody,parentId FROM EmailMessage 
WHERE parentid in:parentIds 
AND Incoming = true
ORDER By parentId
|improve this answer|||||

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.