0
trigger send_notification on students__c (after insert,after update) {

    students__c std = trigger.new[0]; 
    std  = [SELECT id, Course_Name__r.OwnerID FROM students__c  WHERE Id IN: std ];
    EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'info_to_Instructor'];
    String[] toAddresses = new String[] {std.Course_Name__r.instructor__r.email__c}; 
    String[] ccAddresses = new String[] {'**'};
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    mail.setTargetObjectId(std.Course_Name__r.OwnerID);
    mail.setSenderDisplayName('TeacherPortal');
    mail.setUseSignature(false);
    mail.setBccSender(false);
    mail.setSaveAsActivity(false);
    mail.setToAddresses(toAddresses);
    mail.setCcAddresses(ccAddresses);
    mail.setTemplateId(et.id);


    if(Trigger.isAfter){
        if(Trigger.isInsert ){ 
            if(std.Course_Name__c != null) {
                //EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'info_to_Instructor'];
                //mail.setTemplateId(et.id);
                Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});   
            } 

        }
   }
}

Error: Invalid Data. Review all error messages below to correct your data. Apex trigger send_notification caused an unexpected exception, contact your administrator: send_notification: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_TYPE_FOR_OPERATION, Only User, Contact, Lead, or Person objects are allowed for targetObjectId: a0W9000000SNGdQ.: [targetObjectId, a0W9000000SNGdQEAX]: Trigger.send_notification: line 22, column 1

2 Answers 2

1

You need to query inorder to get relation ship field value

students__c std = trigger.new[0];
std  = [SELECT id, Course_Name__r.OwnerID FROM students__c  WHERE Id IN: std.Id ];

and then use mail.setTargetObjectId(std.Course_Name__r.OwnerID);

Note: This will not work for bulk record. Please update your code for bulk operation.

4
  • Error: Invalid bind expression type of Students__c for column of type Id at line 4 column 77 Commented Feb 18, 2016 at 8:23
  • 2
    Replace with : std = [SELECT id, Course_Name__r.OwnerID FROM students__c WHERE Id = :std.Id ]; Commented Feb 18, 2016 at 8:38
  • 1
    @ron Yes.. use std.Id.. chck my updated ans
    – Ratan Paul
    Commented Feb 18, 2016 at 8:47
  • @ron Always welcome
    – Ratan Paul
    Commented Feb 18, 2016 at 10:11
0

I think you should debug Course_Name__r.OwnerID and check that it is right or not. other part of code working well.

You must log in to answer this question.

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