function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Samruddhi GokhaleSamruddhi Gokhale 

Lead auto assignment email getting fired even after setting EmailHeader.triggerUserEmail = false


I have a lead trigger which updates the owner of lead to the currently logged in user whenver any user edits a lead. I have the settings to set EmailHeader.triggerUserEmail = false in 'After Update' trigger. Still the system generated mail is getting fired.
Trigger code is as follows:
trigger LeadTrigger on Lead (after update)
Database.DMLOptions dlo = new Database.DMLOptions();
        dlo.EmailHeader.triggerAutoResponseEmail = false;
        dlo.EmailHeader.triggerUserEmail = false;
        dlo.EmailHeader.triggerOtherEmail = false;
        List<Lead> leadList = new List<Lead>();
        for(Lead leadObj:Trigger.newMap.values())
                leadList.add(new Lead(id=leadObj.Id,ownerId=leadObj.ownerId));
            for(Lead l:leadList)
                if(l.ownerId != Userinfo.getUserId() && Trigger.newMap.get(l.Id).ownerId == Trigger.oldMap.get(l.Id).ownerId)
                    l.ownerId = UserInfo.getUserId();
Samruddhi GokhaleSamruddhi Gokhale
I also have a static variable which does not allow to go this code into endless loop.
Resolution :
The reason why in the above scenario DMLOptions does not work is because it only applies to DML calls made after the DML options are applied. I.e. you would need to generate a list of objects to insert/update and set DMLOptions on them.
As a workaround for the scenario shown above, one could use a @future method like so:
trigger ChangeOwnership_v2 on Case (before update) { 
List<ID> caseIDs = new List<ID>(); 
for (Case c : Trigger.New){ 
if (c.Change_Ownership__c == true){ 
if(caseIDs.size() > 0) { 
Helper class
public class CaseHelper { 

public static void updateOwnership(List<Id> caseIDs) { 
Database.DMLOptions dmo = new Database.DMLOptions(); 
dmo.EmailHeader.triggerUserEmail = false; 

List<Case> casesToUpdate = [select ownerid, change_ownership__c from case where id in :caseIDs]; 

for(Case c : casesToUpdate) { 
c.Change_Ownership__c = false; 

Database.update(casesToUpdate, dmo); // Actual DML operation is performed instead of implicit update

Samruddhi GokhaleSamruddhi Gokhale
This is applicable if you expect the correct behavior with 'before update' trigger. I am doing explicit update in after update trigger (the same that is happening through your future method).