Skip to main content
What is meant by mixed DML exception?   How to avoid this?
3 respuestas
  1. 7 may 2016, 14:17
    Hi,

    Please find the following example -

    Apex Trigger:

    trigger UserTrigger on User (before insert, before update, after update) {

    //Before Triggers

    if(trigger.isBefore) {

    }

    //After Triggers

    else {

    /*** Upon inactivating the user, corresponding opportunity owners should be replaced with

    the inactive users manager ***/

    Map<Id,Id> inActiveUserIdsAndMgrsMap = new Map<Id,Id>();

    for(User usr : trigger.new) {

    if(usr.isActive != trigger.oldMap.get(usr.Id).isActive && !usr.isActive) {

    inActiveUserIdsAndMgrsMap.put(usr.Id,usr.ManagerId);

    }

    }

    if(inActiveUserIdsAndMgrsMap.size() > 0) {

    UserTriggerHandler.processOpps(inActiveUserIdsAndMgrsMap);

    }

    }

    }

    In the above code in the same transaction updating both User (Non setup object), Opportunity (Setup Object), to avoid mixed DML operation using the following logic which is asynchronous -

    Apex Class: 

    public with sharing class UserTriggerHandler {

    @future

    public static void processOpps(Map<Id,Id> inActiveUserIdsAndMgrsMap) {

    List<Opportunity> oppUpdLst = new List<Opportunity>();

    for(Opportunity opp : [select ownerId from Opportunity where ownerId in: inActiveUserIdsAndMgrsMap.keySet()]) {

    opp.ownerId = inActiveUserIdsAndMgrsMap.get(opp.ownerId);

    oppUpdLst.add(opp);

    }

    if(oppUpdLst.size() > 0) {

    update oppUpdLst;

    }

    }

    }

    ------------

    Thanks,

    Srinivas

    - Please mark as solution if your problem is resolved.