+ Start a Discussion
Deepak G 9Deepak G 9 

I am getting two emails from a trigger

Hi All,

I have a before update Trigger and it is sending two emails when changing a case owner. Kindly help me It should send only once.
trigger sendEmailOnOwnerChange on Case (before update)
    Map<Id, Case> map_OldCaseValues = new Map<Id, Case>();
    Map<Id, Case> map_NewCaseValues = new Map<Id, Case>();

    String currentUserId = UserInfo.getUserId();
    Boolean sendMail = false;
    Boolean emailToNewCaseOwner;
    Boolean isEmailToOldAndNewOwner = false;
    for(integer i =0; i<Trigger.New.Size(); i ++)
        if(Trigger.New[i].OwnerId != Trigger.oldMap.get(Trigger.new[i].id).OwnerId)
           /*Requirement 443*/
           Trigger.New[i].Number_of_times_Flash_Displayed__c = 0;
           if(Trigger.oldMap.get(Trigger.new[i].id).OwnerId!= currentUserId && Trigger.new[i].OwnerId == currentUserId )
               emailToNewCaseOwner = false;
        new sendEmailOnOwnerChangeController().notificationStatusForInsert(map_NewCaseValues,map_OldCaseValues,emailToNewCaseOwner,isEmailToOldAndNewOwner);                
I put debuglog and verified it triggered two times
Thanks In Advance,
Gururaj BGururaj B
I think you have either the process builder or workflow on Case object (on update) which in turn updating the case. This would lead to the execution of Trigger multiple times. So you are seeing the email multiple times. If it has helped in any ways to solve your problem please mark as best answer
v varaprasadv varaprasad
Hi Deepak,

Try once like below:
if(Trigger.New[i].OwnerId != Trigger.oldMap.get(Trigger.new[i].id).OwnerId && trigger.isBefore&&Trigger.isupdate)

or create one stattic variable

public class stopRecursion{
public static boolean runOnce = false; 

if(Trigger.New[i].OwnerId != Trigger.oldMap.get(Trigger.new[i].id).OwnerId && stopRecursion.runOnce == false){
  //Do your logic
  stopRecursion.runOnce = True;

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

@For Support: varaprasad4sfdc@gmail.com