Sub topic 5
Writing Data with as user
This chapter assumes you know basic Apex classes, SOQL and DML statements, and how profiles and permission sets grant object permissions (CRUD) and field-level security (FLS). Earlier chapters showed that Apex runs in system mode by default and that WITH USER_MODE enforces permissions on queries. Here you apply the same idea to DML.
Why DML needs its own enforcement
In system mode, insert, update, delete, and undelete succeed even when the running user has no create, edit, or delete permission on the object. They also write to fields the user cannot edit. A class declared with sharing only limits which records the code can see and change. It does not check CRUD or FLS.
User mode closes that gap. When a DML operation runs in user mode, Salesforce checks these for the running user:
- Object permissions: create, edit, or delete on the object.
- Field-level security: edit access to every field you set on the record.
- Sharing: access to the records being changed.
The as user keyword
Add as user between the DML keyword and the record or list. It applies to that one statement only.
public with sharing class ContactService {
public static void createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
insert as user c;
}
}If the user cannot create Contacts, or cannot edit Email, the statement throws a DmlException and no record is saved. The keyword works with insert, update, upsert, delete, and undelete. Other statements in the same method still run in system mode unless you mark them too.
public with sharing class OpportunityService {
public static void closeOpportunity(Opportunity opp) {
opp.StageName = 'Closed Won';
update as user opp;
}
public static void removeOpportunity(Opportunity opp) {
delete as user opp;
}
}Database methods with AccessLevel
The Database class has overloads that take an AccessLevel. Use them when you need partial success, because as user statements are all-or-nothing.
public with sharing class ContactBatchService {
public static List<Database.SaveResult> createContacts(List<Contact> contacts) {
return Database.insert(contacts, false, AccessLevel.USER_MODE);
}
}The second argument, allOrNone, is false here. Records that fail are reported in the returned SaveResult list instead of throwing an exception. The next chapter covers how to read those results.
Choosing between the two forms
| Form | Failure behavior | Use when |
|---|---|---|
| `insert as user records` | Throws `DmlException` for the whole statement | Any failure should stop the operation |
| `Database.insert(records, false, AccessLevel.USER_MODE)` | Returns per-record results | You want valid records saved and failures reported |
Common errors
- Forgetting the keyword on one statement. A method with
insert as userfollowed by a plainupdatestill updates in system mode. Check every DML line. - Setting a field the user cannot edit. Even a field you set only for convenience, such as a default value, causes the whole statement to fail if FLS blocks it. Remove fields the user cannot edit, or set them in a deliberate system mode step.
- Assuming
with sharingis enough. It controls record access only. Useas userorAccessLevel.USER_MODEfor CRUD and FLS. - Expecting a partial save from
as user. If one record in a list fails the permission check, the statement fails. Use theDatabaseoverload withallOrNoneset tofalse.
Exercise
A method runs insert as user contacts; on a list of 200 Contacts. The running user lacks edit access to the Contact Email field, and every record sets Email. What happens, and how would you change the code so that records without an email still save while failures are reported?
Show answer
The statement throws a DmlException and none of the 200 records are saved, because the field check fails and as user is all-or-nothing. Change the call to Database.insert(contacts, false, AccessLevel.USER_MODE) and inspect the returned SaveResult list. Records that set Email fail with a per-record error, while records that leave it empty are saved.
Exercise
A class is with sharing and contains update acc; for an Account the user can see but cannot edit under their profile. Does the update succeed? Show the one-word-change fix.
Show answer
Yes, it succeeds, because with sharing does not check object permissions or FLS and the code runs in system mode. Change it to update as user acc;, which then throws a DmlException for a user without edit access.