Unassign the Permission Set Using Apex Trigger for Users - DevFacts | Tech Blog | Developer Community | Developer Facts

Unassign the Permission Set Using Apex Trigger for Users – DevFacts | Tech Blog | Developer Community | Developer Facts

1 Min Read

Permission sets offer a method to manage Salesforce access. With Apex, we can dynamically assign and unassign permissions 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;
    }
}

In this trigger, we first retrieve a list of all PermissionSetAssignment records associated with the user being updated in our Salesforce org.

If the list is not empty, indicating the user has assigned permission sets, we delete the PermissionSetAssignment records, effectively removing the permission sets from the user. This before update trigger on the User object catches changes to the user and unassigns the permission sets before the updates are saved to the database.

You might also like