Development questions
How do Mixed DML Errors happen in triggers (e.g., creating a User and an Account in the same transaction) and how do you resolve them?
Mixed DML error (MIXED_DML_OPERATION) occurs when setup objects (User, Group, GroupMember, PermissionSetAssignment, UserRole, etc.) and non-setup objects (Account, Contact, custom objects) are modified in the same transaction.
Solutions:
- Move the setup-object DML (or the non-setup one) to a separate transaction using
@futureor Queueable Apex. - In tests, wrap one side in
System.runAs().
apex
@future
public static void assignPermSet(Set<Id> userIds) { /* insert PermissionSetAssignment */ }
apex-triggertriggermixed-dmlasync
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?