To fix MIXED_DML_OPERATION error(setup and non-setup objects) in Salesforce

The following error will be occured if you’re trying to perform DML operation on both setup and non-setup objects in the same transation.

` MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): CustomObject__c, original object: User: [] `

Here is the sample code that can explain this case.

Setup objects

So, which objects are setup objects in Salesforce?
Setup objects are the sObjects that affect the user’s access to records in the organization. For operations with correct access-level permissions, you must insert or update these types of sObject in a different transaction.

Here are examples of the Setup Objects:
・ObjectPermissions
・PermissionSet
・PermissionSetAssignment
・QueueSObject
・Territory
・UserTerritory
・UserRole
・User
    fields: UserRoleId, IsActive, ForecastEnabled, IsPortalEnabled, Username, ProfileId

Solution

To fix this kind of error, you can perform DML operations on more than one transation, e.g. using a Future method.


Happy Coding!

Reference :
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dml_non_mix_sobjects.htm

Related Post

To fix “portal account owner must have a rol... In Salesforce, if you're trying to run Unit Test with a Non-Role user, which includes part of creating Portal / Community User test data, the following error will be occured, that is because the portal account's owner does not have a role to be assigned. System.DmlException: Insert failed. First e...