User-mode DML with `insert as user`
Security & deployment · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Insert one tagged Account with `insert as user` so the save honours the running user's field-level and object permissions. Then prove the row saved by querying it by Id.
Lesson
Why this matters
Plain insert runs in system mode and can write fields the running user cannot create. insert as user acct; applies field-level security and sharing. A disallowed field throws SecurityException in the test, not later in production. Admins still pass, because they can create the Account.
The smallest working example
insert as user acct;
Integer savedCount = [SELECT COUNT() FROM Account WHERE Id = :acct.Id];
The saved Id is set only after the DML succeeds.
Name the parts
- **
tag** is already on the starter Account Name. - **
insert as user acct;** is the required syntax, on its own line. Plaininsertdoes not count. - Query **
WHERE Id = :acct.Id** to prove that exact row saved. - Print **
Saved count:,Id present:, andName match:**.
A common wrong version
insert acct;
The row saves, but the save ignored user permissions. The shape check fails.
The fix
Use insert as user acct;, then query by the new Id and by Name.
Now you try
The starter builds the Account. Insert it as the user and print the three lines.
Learn more
The challenge
Insert one tagged Account as user and prove it saved.
Examples:
- a tagged Account is saved →
Saved count: 1 - the saved Account has an Id →
Id present: true - a count by Name on the tag is 1 →
Name match: true
Requirements:
- Uses
insert as usershould be present: the DML isinsert as user <var>;. - Queries by the saved Id should be present: a query uses
WHERE Id = :<var>.Id. - Account saves should be printed as
Saved count: 1. - Id was set by DML should be printed as
Id present: true. - Account visible by Name too should be printed as
Name match: true.
Starter code
String tag = 'AS-S305-' + UserInfo.getUserId() + '-' +
String.valueOf(Datetime.now().getTime());
Account acct = new Account(Name = tag);
Related drills
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Build a secure Account service · Gate work behind a feature flag ›