Sub topic 13
Creating users and assignments with Apex
This chapter assumes you know the required user fields, how profiles and permission sets work, and basic Apex and SOQL. You will insert a user in code and then link a permission set to that user.
When Apex makes sense
Setup, Add Multiple Users and Data Loader cover most needs. Apex fits when user creation is part of a larger process. Examples are provisioning from an onboarding flow, seeding test data in a sandbox, or building users inside a test class.
The code follows the same rules as the Setup screen. The profile's licence must have free capacity, the username must be unique across all Salesforce orgs, and every required field must be set.
The creation flow
A user and its extra access are two separate records. You insert the User first. Then you insert a PermissionSetAssignment that points at the new user's ID.
The example
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);Replace Your_Permission_Set_API_Name with the API name of a real permission set. The query uses the Name field, which holds the API name. The Label field holds the display name.
What each part does
- The profile query returns the ID, not the name.
ProfileIdneeds the ID. - The
Alias,TimeZoneSidKey,LocaleSidKey,EmailEncodingKeyandLanguageLocaleKeyvalues are required. Leaving one out causes aREQUIRED_FIELD_MISSINGerror. insert upopulatesu.Id. The assignment needs that ID, so the order matters.PermissionSetAssignmenttakes the user inAssigneeIdand the permission set inPermissionSetId.
Gotchas
- Mixed DML.
UserandPermissionSetAssignmentare setup objects. Inserting them in the same transaction as a non-setup object, such as an Account, raises aMIXED_DML_OPERATIONerror. Split the work withSystem.runAs()in tests, or move one part to an asynchronous method such as@futureor Queueable. - Permission set licences. If the permission set requires a permission set licence, assign that licence first, using a
PermissionSetLicenseAssignrecord. Otherwise the assignment insert fails. You can check capacity with thePermissionSetLicensequery shown earlier. - Duplicate assignments. Inserting the same user and permission set pair twice fails. Query existing assignments first if the code may run more than once.
- Governor limits. Query the profile and permission set once, outside any loop. For many users, build lists and insert them in bulk.
Bulk version
To create several users, put them in a List<User> and call insert once. Then build a List<PermissionSetAssignment> using each user's ID and insert that list once as well.
Exercise
Why must the Apex code insert the User before it creates the PermissionSetAssignment, and which field links the two?
Show answer
The assignment needs the new user's ID, which only exists after the insert. The AssigneeId field of PermissionSetAssignment holds that user ID.
Exercise
A test class inserts an Account and then a User in the same method and fails with MIXEDDMLOPERATION. What is one way to fix it?
Show answer
Wrap the User insert in System.runAs() with another user so it runs in a separate context, or move one of the operations to asynchronous code.