MIXED_DML_OPERATION error in Salesforce Apex Trigger when updating user objects

I have a trigger on a Contact object, and when I try to update a user record in this trigger, I get the following exception:

"MIXED_DML_OPERATION, DML operation on the configuration object is not allowed after updating the object without installation (or vice versa): User, source object: Contact"

Launch Code:

trigger UpdateContactTrigger on Contact (after update) {

    User u = [SELECT Id, IsActive FROM User WHERE IsActive = true];

    u.IsActive = false;
    update u;

}

How can I avoid this error when updating user record fields from a Contact trigger?

+3
source share
2 answers

Salesforce . - , Contact - . Salesforce DML, .

DML- @future, .

@future , User , @future, Salesforce @future @future.

, , User.

API 15.0 Salesforce User . , User standard, " " User.

User IsActive, IsActiveProxy :

trigger UpdateContactTrigger on Contact (after update) {

    User u = [SELECT Id, IsActive FROM User WHERE IsActive = true];

    u.IsActiveProxy__c = false;
    update u;

}

" " , :

trigger BeforeUpdateUserTrigger on User (before update) {

    for(User user : trigger.new) {

        if(user.IsActive != user.IsActiveProxy__c) {
            user.IsActive = user.IsActiveProxy__c;
        }

    }

}

! .

+9

@future, .

@future
updateUser(){
    User u = [SELECT Id, IsActive FROM User WHERE IsActive = true];

    u.IsActive = false;
    update u;
}

:

trigger UpdateContactTrigger on Contact (after update) {
    updateUser();
}    
+2

All Articles