You need to sign in to do that
Don't have an account?
Emails being fired twice on trigger
Hello all!
This is my first foray into the world of Apex coding. I'm not very famiiliar with coding so appologies in advance for simple errors!
I have put the below trigger together piecing various bits of code accross various forums together to trigger an email to the creator of a task on completion if that task is assigned to another person. It works great! However, the user gets two emails each time - is there a way around this? I did a search on the forum and coultn't find a previous thread which shared similat code to my own.
Thanks!
Louis
Here's the code:
trigger Trigger_Request_CompletedAfterInsertAfterUpdate on Task (after update)
{
Task[] completedTasks = Trigger.new;
for(Task t : completedTasks){
if(t.OwnerId!=t.CreatedById && t.Status=='Completed'){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(t.CreatedById);
mail.setSubject('Task Completed');
mail.setPlainTextBody(Datetime.now().format('MM/dd/yyyy hh:mm a')+' \r\n'+t.Description+' \r\n'+' \r\n'+'Salesforce link: \r\n'+'https://emea.salesforce.com/'+t.AccountId);
mail.saveAsActivity = false;
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
Do you have any workflow field updates on task? Because as per the order of execution, all before & after triggers will be executed first, then workflow field udpates will be executed which will again fire the triggers. If this is the scenario, then you can use a static variable in your trigger to send the email only once.
But I would recommend to use workflows to send emails rather than triggers.
after looking into the code i did not find any mistake
but my doubt is on for(Task t : completedTasks){
could you check with the completedTasks List is having single task or multiple for a single user.
The idea is to have a static variable which will sustain its value across different executions of the trigger for a single transaction.
Use something like this.
And the class would be
Please note that although this is albeit working mechanism, it does have some minor flaws. There was another thread which had detail on using static sets to use a better design, but I cant find it now.