+ Start a Discussion
Rajat MahajanRajat Mahajan 

Mixed DML Operation in a trigger on user object

Hi all,


i have the following piece of code which runs when i try to deactivate a user :



trigger closeTargetProspect on User (after Update) {

public List<Targets__c> Target_list = new list<targets__c>();

for (User u : trigger.new) {

if(!u.isActive) {

Target_list=[select id,Target_Start_Date__c, Target_End_Date__c, Contact_Owner__c from Targets__c where ownerid = :u.id and Target_End_Date__c = null];

for(targets__c t : Target_list)
    t.Target_End_Date__c= date.today();
    update Target_List;





When i deactivate the user, i get an error message :


Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger closeTargetProspect caused an unexpected exception, contact your administrator: closeTargetProspect: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a09900000022LPDAA2; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Targets__c, original object: User: []: Trigger.closeTargetProspect: line 17, column 1


I had read some articles on MIXED_DML_OPERATION on community, but i am unable to get how to change this code to make it work


a piece of code i had found was :




private static void myFunc()


     ///1st DML operation


     User usr = [Select id from User where Id = :UserInfo.getUserId()];













private static void myFunc2()


   ///2nd DML operation





I am not sure how to implement the methods in this trigger or how to make a call from this trigger to a seperate class where this method belongs.


Could you please help me out with changing the code?


Thanks in Advance


Rajat MahajanRajat Mahajan

Hi All,


Correct me if i am wrong,


i did understand that we cannot do a DML operation on a setup object (user) if we are .doing a dml operation on a non setup object (target__c) in the above case.


What i did find out was, while trying to deactivate the user, i was not only not allowed to do the transaction on the first object, but the first transaction (on taget__c) was also not happening





Just put the logic for updating the target__c in a future method and call that method from your trigger. It should work. You don't need to use System.runas or test.start/stop methods as these methods are intended for test classes. 

The first transaction is also not successful because salesforce will commit the changes to database only if the transaction is completely successful (without any errors).