6

I would like to send an email by using email template before delete a specific record. I'm using a before delete trigger and I receive the email, the problem is that the email is almost empty, without any record details. The same email template is used for after update and it works fine (record details are correctly sent). Any suggestions?

trigger opportunityNotificheOAS on Opportunity (before delete, after update) {
    if(Trigger.isDelete){ 
        for(Opportunity o : Trigger.old){ 
            emails.add(prepareEmail(o)); 
        } 
    } 

In the prepareEmail method I do the following:

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId(et.id); mail.setTargetObjectId(c.Id); mail.setWhatId(o.Id);
5
  • Welcome to the community! You may be asked for a code sample so we can see how you're using the template; can you provide that?
    – Mike Chale
    Commented Feb 28, 2013 at 17:28
  • Are you using trigger.old? I suspect this is your problem. Could you post your code?
    – greenstork
    Commented Feb 28, 2013 at 17:33
  • trigger opportunityNotificheOAS on Opportunity (before delete, after update) { if(Trigger.isDelete){ for(Opportunity o : Trigger.old){ emails.add(prepareEmail(o)); } } In the prepareEmail method I do the following: Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTemplateId(et.id); mail.setTargetObjectId(c.Id); mail.setWhatId(o.Id);
    – Ivano
    Commented Feb 28, 2013 at 17:39
  • Hard to tell without seeing more of your code, like the emails object and the prepare email method in it's entirety.
    – greenstork
    Commented Feb 28, 2013 at 17:52
  • @Ivano: If LaceySnr answered your question please mark his response as the answer.
    – Mike Chale
    Commented Mar 1, 2013 at 13:50

2 Answers 2

1

I think the problem is that the email generation and sending takes place in a separate after your code has run, and by that time the record you're interested in doesn't exist.

I would have a delete flag on the object which when checked means an email is sent (via an update trigger) and then use a time-baed workflow or a scheduled batch apex job to do clean up afterwards, removing all records where that checkbox is true.

1

Thank you @LaceySnr, you were right, the problem was due to the fact that the send email method was separated from the if(Trigger.isDelete){} section and the record was already deleted at sending time. I solved the issue preventing the record deletion by revaluate if(Trigger.isDelete){ system.debug('xxx');}

You must log in to answer this question.

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