Sub topic 13
Creating Users and Assignments with Apex
Apex can create users and assign access in a single transaction. This suits provisioning from a trigger-free service class, a post-copy sandbox script, or an integration that onboards people from an HR system. This chapter covers the objects involved, a bulk-safe pattern, and the errors you are most likely to hit.
Prerequisites
This chapter assumes you have read the earlier chapters on licences, profiles, permission sets and required user fields. You also need:
- The Manage Users permission, plus Author Apex if you want to save classes.
- Working knowledge of SOQL, Apex DML and
Database.SaveResult. - A sandbox or Developer Edition org. Do not run these examples in production while you are learning.
The objects involved
Provisioning in Apex touches a small set of objects. All of them are setup objects, meaning they store configuration rather than business data.
| Object | Purpose | Key fields |
|---|---|---|
| `User` | The person record | `ProfileId`, `Username`, `Alias`, `Email`, `LastName`, locale and encoding fields |
| `Profile` | Sets the user licence | `Name`, `UserLicenseId` |
| `PermissionSet` | Extra access | `Name` (API name), `IsOwnedByProfile`, `LicenseId` |
| `PermissionSetAssignment` | Links a user to a permission set or group | `AssigneeId`, `PermissionSetId`, `PermissionSetGroupId` |
| `PermissionSetLicense` | Capacity for a feature licence | `DeveloperName`, `TotalLicenses`, `UsedLicenses` |
| `PermissionSetLicenseAssign` | Links a user to a permission set licence | `AssigneeId`, `PermissionSetLicenseId` |
The user licence is not set directly on the user. It comes from the profile you choose, so the profile must match a licence that still has capacity.
A minimal example
This snippet inserts one user and assigns one permission set. Replace the permission set API name with a real one before you run it.
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
FirstName = 'Ada',
LastName = 'Lovelace',
Alias = 'alove',
Email = '[email protected]',
Username = '[email protected]',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US'
);
insert u;
PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = 'Your_Permission_Set_API_Name' LIMIT 1];
insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);Three details are easy to miss:
NameonPermissionSetis the API name, not the label. QueryLabelif you only know what appears in Setup.- The username must be unique across all Salesforce orgs. It looks like an email address but does not have to be a working one.
- By default, inserting a user through Apex does not send the welcome email. The new user cannot sign in until a password is set or the email is triggered, as shown in the next section.
A bulk-safe pattern
The minimal example uses two DML statements for one user. Calling it in a loop would burn through the limit of 150 DML statements per transaction after about 75 users. Collect records into lists and run one DML statement per object instead.
public with sharing class UserProvisioner {
public class ProvisionException extends Exception {}
public static List<String> provision(List<User> newUsers, String permSetName) {
List<String> errors = new List<String>();
List<PermissionSet> sets = [
SELECT Id FROM PermissionSet
WHERE Name = :permSetName AND IsOwnedByProfile = false
LIMIT 1
];
if (sets.isEmpty()) {
throw new ProvisionException('Permission set not found: ' + permSetName);
}
Database.DMLOptions opts = new Database.DMLOptions();
opts.optAllOrNone = false;
opts.emailHeader.triggerUserEmail = true;
List<Database.SaveResult> results = Database.insert(newUsers, opts);
List<PermissionSetAssignment> assignments = new List<PermissionSetAssignment>();
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
assignments.add(new PermissionSetAssignment(
AssigneeId = newUsers[i].Id,
PermissionSetId = sets[0].Id
));
} else {
errors.add(newUsers[i].Username + ': ' + results[i].getErrors()[0].getMessage());
}
}
for (Database.SaveResult sr : Database.insert(assignments, false)) {
if (!sr.isSuccess()) {
errors.add('Assignment failed: ' + sr.getErrors()[0].getMessage());
}
}
return errors;
}
}Call it from anonymous Apex:
Id profileId = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1].Id;
List<User> batch = new List<User>();
for (String last : new List<String>{'Hopper', 'Turing'}) {
batch.add(new User(
LastName = last,
Alias = last.left(8).toLowerCase(),
Email = last.toLowerCase() + '@example.com',
Username = last.toLowerCase() + '@example.com.demo',
ProfileId = profileId,
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US'
));
}
System.debug(UserProvisioner.provision(batch, 'Your_Permission_Set_API_Name'));Key design choices in this pattern:
- Partial success.
optAllOrNone = falselets valid users save while invalid ones are reported. Usetrueif the batch must succeed or fail as a unit. - Result order.
SaveResultobjects come back in the same order as the input list, so you can use the index to match a failure to its record. Successful inserts also populateIdon the originalUserobjects. - Welcome email.
triggerUserEmail = truesends the new user an email with a link to set a password. Leave itfalsewhen the org uses single sign-on and users never need a Salesforce password. - Profile-owned permission sets. Every profile has a hidden permission set with
IsOwnedByProfile = true. You cannot assign those, so the query excludes them.
Permission set licences come first
Some permission sets require a permission set licence. If the user does not already hold that licence, the PermissionSetAssignment insert fails. Assign the licence first:
PermissionSetLicense psl = [
SELECT Id, TotalLicenses, UsedLicenses
FROM PermissionSetLicense
WHERE DeveloperName = 'Your_PSL_Developer_Name'
LIMIT 1
];
if (psl.UsedLicenses < psl.TotalLicenses) {
insert new PermissionSetLicenseAssign(
AssigneeId = u.Id,
PermissionSetLicenseId = psl.Id
);
}Checking capacity in Apex gives a clear message instead of a generic DML failure. The count is a snapshot, so another process could take the last licence between your query and your insert. Still check the SaveResult.
Assigning a permission set group
A permission set group is assigned through the same PermissionSetAssignment object. Set PermissionSetGroupId instead of PermissionSetId.
PermissionSetGroup psg = [
SELECT Id FROM PermissionSetGroup
WHERE DeveloperName = 'Your_Group_Developer_Name'
LIMIT 1
];
insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetGroupId = psg.Id);A group must be in the Updated status to be usable. A group that is still recalculating can delay when the access takes effect, so avoid tests that assume access immediately after assignment.
Mixed DML errors
Salesforce does not allow setup objects (such as User) and non-setup objects (such as Account) to be changed in the same transaction. Doing so throws MIXED_DML_OPERATION. Your provisioning class avoids this because it only touches setup objects. The problem appears when you also create business records, and in tests.
- In production code, move the second kind of DML into a
Queueableor@futuremethod so it runs in a separate transaction. - In test classes, wrap the setup DML in
System.runAs():
@IsTest
private class UserProvisionerTest {
@IsTest
static void createsUserAndAssignment() {
User admin = new User(Id = UserInfo.getUserId());
System.runAs(admin) {
Account a = new Account(Name = 'Test Co');
insert a;
// User and PermissionSetAssignment DML can safely follow here.
}
System.assertEquals(1, [SELECT COUNT() FROM Account WHERE Name = 'Test Co']);
}
}Common failures
| Status code or symptom | Likely cause | Fix |
|---|---|---|
| `DUPLICATE_USERNAME` | The username exists in any Salesforce org | Add a suffix such as `.demo` or `.sandboxname` |
| `LICENSE_LIMIT_EXCEEDED` | The profile's user licence has no free seats | Deactivate unused users or buy more licences |
| `REQUIRED_FIELD_MISSING` | A required field such as `Alias` or `TimeZoneSidKey` is null | Populate all ten fields in the examples |
| `INVALID_CROSS_REFERENCE_KEY` | `ProfileId` is wrong or from another org | Query the profile by name in the current org |
| `STRING_TOO_LONG` | `Alias` is longer than 8 characters | Use `left(8)` |
| `MIXED_DML_OPERATION` | Setup and non-setup DML in one transaction | Separate transactions or `System.runAs` |
| Duplicate error on assignment | The user already has that permission set | Query existing assignments and skip them |
To avoid duplicate assignments in repeat runs, query existing records first:
Set<Id> alreadyAssigned = new Set<Id>();
for (PermissionSetAssignment a : [
SELECT AssigneeId FROM PermissionSetAssignment
WHERE PermissionSetId = :permSetId AND AssigneeId IN :userIds
]) {
alreadyAssigned.add(a.AssigneeId);
}When Apex is the wrong tool
Apex is not always the best option:
- For a one-off load of a few hundred users, Data Loader with a CSV is simpler and needs no code deployment.
- For ongoing onboarding from an identity provider, Just-in-Time provisioning or SCIM keeps users in sync without custom code.
- Apex gives you the most control when you need conditional logic, such as choosing the permission set from a department value, or when you need error handling that other tools cannot provide.
Whichever route you use, keep least privilege in mind. Give new users the minimum profile and add access through permission sets, so a mistaken script grants less rather than more.
Exercise
A loop inserts 200 users one at a time, and each iteration also inserts one PermissionSetAssignment. The job fails partway through. What limit does it hit, and how do you fix it?
Show answer
It exceeds the limit of 150 DML statements per transaction, because each iteration uses two statements. Collect the users in a list, insert them with one Database.insert call, then build a list of PermissionSetAssignment records from the successful results and insert that list with a second call. This uses two DML statements in total.
Exercise
Your code inserts a PermissionSetAssignment for a permission set that requires a permission set licence, and the insert fails. The user was created successfully. What is the most likely cause and the fix?
Show answer
The user does not hold the required permission set licence. Query PermissionSetLicense to check that UsedLicenses is below TotalLicenses, insert a PermissionSetLicenseAssign record for the user, then insert the PermissionSetAssignment.
Exercise
A test method inserts an Account and then a User, and fails with MIXEDDMLOPERATION. How do you fix it?
Show answer
Wrap the DML in System.runAs(new User(Id = UserInfo.getUserId())) so the setup and non-setup operations run in separate contexts. In production code, move one of the operations into a Queueable or @future method.