You need to create a user and assign permission sets when a contact is approved. The code fails with a mixed DML error. Why, and what do you do?
Your confidence:Not rated
Model answer
Why: DML on setup objects (User, PermissionSetAssignment, Group membership) and non-setup objects (Contact) in the same transaction isn't allowed, because setup changes affect sharing and access calculations.
Fix
- Keep the contact update in the current transaction.
- Move user creation and permission set assignment to async: a Queueable (preferred: job ID, objects as input, Finalizer for failures) or a
@futuremethod with IDs. - Make it idempotent: check whether the user already exists (by federation ID or username) before creating.
- Report failures (for example duplicate username) back to the contact record or a log, because the user won't see an async error.
- Tests: wrap setup DML in
System.runAs(adminUser)in tests to avoid the same error in test setup.
โ Key points to hit
โ Red-flag answers
- Trying to catch the mixed DML exception
- Doing both in one synchronous transaction with a workaround hack
โช Follow-ups
Which objects count as setup objects?
Objects that affect access: User, Group, GroupMember, QueueSObject, PermissionSet(Assignment), territory assignment objects and a few others. The documentation lists them.
Could Flow avoid the problem?
Flow hits the same rule. Run the user-creation part in a separate transaction, for example a scheduled path in a record-triggered flow, or an asynchronous invocable Apex action.