• damienphillippi1.3915403128946355E12
  • NEWBIE
  • 5 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi everyone.

Can you please help me to fix this error: I have a trigger that would send an email alert to new AssignedTo user. But it through an error if the Site Defect is a new record. in other word when the Trigger.old[0].Assigned_To__c is empty. 

here is the code:

trigger SendEmailAlertToAssignedTo on Site_Defects__c (after insert, before update) { // I have the error message here

    if(Trigger.new[0].Assigned_To__c != Trigger.old[0].Assigned_To__c ) {
       
            //Sending Mail
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;
          
                //Setting user email in to address
            String userName = Trigger.new[0].Assigned_To__c;
             
            User AT = [Select Email From User where id= : userName ]; 
            String userEmail = AT.Email;
          
          
            //String email = Trigger.new[0].RegionalManager__c;
            String[] toAddresses = new String[] {userEmail} ;
          
            // Assign the addresses for the To and CC lists to the mail object
            mail.setToAddresses(toAddresses );
            mail.setToAddresses(MyEmail);
          
            //Email subject to be changed
            mail.setSubject('THIS IS A TEST. Site Defect Owner Changed');
            String body = AT.Email+'The owner of Site Defect ' + trigger.Old[0].Name +' has been changed <br> <br>'+
            'Regards <br> ';
            //Body of email
            mail.setHtmlBody(body);
          
            //Sending the email
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
}

Thank you.