3

Background: I am trying to make a UI that will simplify managing assignments of some custom permissions against permission sets in my managed package. This section of the managed package would only be used by an admin.

Here is what I'm trying to figure out:

What is the best way to programmatically determine in APEX if a custom permission is assigned to a given permission set?

Once I know what custom permissions a permission set has, how do I programmatically add or remove custom permissions to it?

I hope that all of the above could be done with some simple SOQL queries once I understand how it fits together.

6

While I was composing this question I figured it out.

Since it took me longer to figure out than I would have liked, I will share what I learned in case it helps someone else down the road.

It turns out that the connection between CustomPermission and the PermissionSet is made via the object called SetupEntityAccess.

You can look up if a custom permission is enabled to a permission set like so:

 private static Boolean isThisCustomPermissionEnabled(String customPermissionName, PermissionSet myPermissionSet){
     CustomPermission customPermission = [SELECT Id FROM CustomPermission WHERE DeveloperName = :customPermissionName];
     List<SetupEntityAccess> isPermissionSetEnabled = [SELECT Id FROM SetupEntityAccess WHERE ParentId = :myPermissionSet.Id AND SetupEntityId = :customPermission.Id];
     return !isPermissionSetEnabled.isEmpty();
 }

To add/remove a custom permission from a permission set:

List<PermissionSet> myPermissionSet = [SELECT Id FROM PermissionSet WHERE Label = :permissionSetLabel];
List<CustomPermission> customPermission = [SELECT Id FROM CustomPermission WHERE DeveloperName = :customPermissionName];

if(addNewPermission){
   SetupEntityAccess enablePermission = new SetupEntityAccess(ParentId=myPermissionSet[0].Id, SetupEntityId=customPermission[0].Id);
   insert enablePermission;
}
else{
   List<SetupEntityAccess> permissionToRemove = [SELECT Id FROM SetupEntityAccess WHERE ParentId = :myPermissionSet[0].Id AND SetupEntityId = :customPermission[0].Id];
   delete permissionToRemove[0];
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.