function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
WrogWrogWrogWrog 

Can I update the EmailMessage status in an apex trigger?

Still a newbie to Apex (in fact, a newbie to "proper" code writing at all). Can't see a simple answer to my question, so here goes with a discussion topic.
 
We would like to set the status of any "new" (unread) emails attached to a case to "read" at the point of closing a case. Can I actually do this?
 
My current trigger is as below. If I understand the log, it fails (with an unknown error) at the line highlighted in red. Is this because I can't do that, or becuase I'm doing it wrong?
 
I've been told I should be able to change the status of an email remotely, but I could imagine this might not be "good practice".
 
Roger England
 
Code:
trigger Case_CloseEmailComment_update on Case (before update) {

 Case[] cs = Trigger.new;
 
 if (cs[0].Status == 'Closed' ) {
  ID csId = cs[0].Id; 
  
  if (cs.size() > 0){
   cs[0].HasCommentsUnreadByOwner = false;
 
   EmailMessage[] ems = [select Id, Status from EmailMessage where (ParentId = :csId)]; 
   if (ems.size() > 0){
    for (EmailMessage em: ems){
     if (em.Status == '0'){
      em.Status = '1'; 
      update em;
     }
    }
   }
  }
 }
}

lopezclopezc
Hi,

I am having the same problem, everytime I want to update the status I get un unexpected error. Did you find the answer?
WrogWrogWrogWrog
I don't know what it takes to get an answer to such a simple yes/no question. There are so so many places to ask the question, but I can't see what magic words you need to use to get and answer from the learned community - some more recent and more esoteric queries attract much more attention. Feeling a bit of an outsider! Is it because I'm not American?
lopezclopezc
Hi,

I think I know why.. Email Message is not editable so you can't update it.

I am right?
WrogWrogWrogWrog
It certainly looks as if I can't update it, but I'd love someone, ANYONE from salesforce to confirm that to me. It's a pain in the neck not being able to update the status of an email through code, since the only other way is to open every **** email individually!