
Permission sets allow for managing Salesforce access, and using Apex, we can dynamically assign or unassign 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;
}
}
In this trigger, we retrieve all PermissionSetAssignment records linked to the user being updated in Salesforce.
If the list is not empty, meaning the user has assigned permission sets, we delete the PermissionSetAssignment records, unassigning the permission sets. The trigger uses a before update on the User object to handle changes and unassign permission sets before updates are saved in the database.