Unassign the Permission Set Using an Apex Trigger for the User

Unassign the Permission Set Using an Apex Trigger for the User

1 Min Read

Permission sets allow manipulation of Salesforce access, and using Apex, you can dynamically assign or unassign them for users.

Here’s an example of unassigning a permission set from a user using an Apex trigger:

“`
trigger UnassignPermissionSet on User (before update) {
List psaList = [SELECT Id, PermissionSetId, AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Trigger.Old[0].Id];
if (!psaList.isEmpty()) {
delete psaList;
}
}
“`

This trigger retrieves all `PermissionSetAssignment` records linked to the user being updated. If the list isn’t empty, indicating the user has permission sets assigned, it deletes the `PermissionSetAssignment` records, thus unassigning the permission sets. The `before update` trigger on the `User` object detects user changes and unassigns the permission sets before the updates are saved to the database.

You might also like