I want to send an email template to a contact record, based upon QuoteItem field. On the QuoteItem object I have a field called update_del
(checkbox). When the field is set true, I want to send an email template.
The QuoteItem is child object to the Quote object, having master-detail relationship.
On the Quote object I have a field called Email__c
and I want to send an email template to the address which is set in that field.
I tried the code Below, but I am getting an error when executing the SOQL Query
trigger emailtemplate2 on Quote_Item__c(after update)
{
List<Quote_Item__c> oList = Trigger.new;
List<Quote_Item__c> nList = trigger.old;
if(oList[0].Updated_del__c !=nList[0].Updated_del__c) {
Set<Id> QuoteItemIds= new Set<Id>();
List<Quote__c> sList = [
select id,Email__c
from Quote__c
where Quote__r.Email__c =:nList[0].Quote__c.Id
limit 1
];
// Error Occuring Point
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
if(oList[0].Quote_Item__c== 'true') {
EmailTemplate et=[Select id from EmailTemplate where name = 'quote3' limit 1];
mail.setTemplateId(et.id);
mail.setToAddresses(new String[] {sList[0].email});
mail.setTargetObjectId(sList[0].id);
mail.setSaveAsActivity(false);
Messaging.SendEmailResult [] r = Messaging.sendEmail(
new Messaging.SingleEmailMessage[] {mail});
}
}
}
Best Answer
There are a few issues with the trigger:
1) Trigger is not bulkified - the current code will only work when you update 1 record at a time. Have a read here and here.
2)
nList[0].Quote__c.Id
-Quote__c
is the same asQuote__r.Id
(__r and not __c, but then you won't have access to parent related fields usingtrigger.old
- only fields on the same sObject). In order to get parent record's fields you need to run a SOQL query.3)
where Quote__r.Email__c =:nList[0].Quote__c.Id
- Doesn't make any sense. You are comparing an email string to a record ID, did you meanwhere Quote__c = :nList[0].Quote__c
?