• kamusarea
  • NEWBIE
  • 0 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 2
    Replies
Hey guys,
 
I'm pretty new to Apex programming and am just trying to understand something that our consultants wrote for us.
The code snippet is below:
 
Code:
trigger trg_custom1_req on custom1__c (after update) {
   for (custom1__c evalRec:System.Trigger.new) 
   {

      custom1__c oldEvalRec = System.Trigger.oldMap.get(evalRec.Id);
      if (!oldEvalRec.Evaluation_Approved__c && evalRec.Evaluation_Approved__c)
      {
         String templateId = '00X70000000XXXX';
         Opportunity oppRec = [SELECT Id, Account.Owner.Id, Account.Owner.Email ,Account.Owner.Alias_Email__c FROM Opportunity WHERE Id = :evalRec.Opportunity__c];
         String toEmail = oppRec.Account.Owner.Alias_Email__c;
         if (toEmail == null)
            toEmail = oppRec.Account.Owner.Email;
         String[] toEmailId = new String[] {toEmail};
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
         mail.setToAddresses( toEmailId );
         mail.setWhatId (evalRec.Id);
         mail.setTemplateId (templateId);
         mail.setTargetObjectId ('003R0000001XXXX'); // Admin Contact         
         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
      }
   }
}

So everything works just fine but the admin email in the mail.setTargetObjectId ('003R0000001XXXX'); is always emailed. I'd like to change this such that it is only emailed if the oppRec.Account.Owner.Alias_Email__c is null...
 
So I modified the code to add an if statement:
Code:
if (oppRec.Account.Owner.Alias_Email__c == null)
   mail.setTargetObjectId ('003R0000001XXXX'); // Admin Contact         

 However, SFDC then returns this on the trigger execute:
 
Validation Errors While Saving Record(s)

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger trg_custom1_req caused an unexpected exception, contact your administrator: trg_custom1_req : execution of AfterUpdate caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template: Trigger.trg_prod_eval_req: line 22, column 13".

However, this link http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm suggests to me that the setTargetObjectId is optional.

What am I missing here?

Thanks a bunch.
Frank.


 

 
  • August 28, 2008
  • Like
  • 0