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];
}