How to assign Profile User to a Permission Set in Apex?
It often happens that one of my customers wants to have a new permission set created and at the same time wants the users of one or more profiles assigned to this new permission set. This is easily done with the code below.
Snippet
//Get all needed Profiles in a Map
Map<Id, Profile> mapOfProfilesByIds = new Map<Id, Profile>([SELECT Id, Name FROM Profile
WHERE Name = 'Profile Name1' OR Name = 'Profile Name2']);
//Get all PermissionSetAssignments which are related to the upper Profiles
List<PermissionSetAssignment> listOfPermissionSetAssignments = [SELECT Id, AssigneeId FROM PermissionSetAssignment
WHERE PermissionSet.ProfileId =: mapOfProfilesByIds.keySet() AND Assignee.IsActive = TRUE];
//Get Permission Set Id
Id newPermSetId = [SELECT Id FROM PermissionSet WHERE Name = 'Perm_Set_Name'].Id;
//Create new PermissionSetAssignments with all the User in the upper PermissionSetAssignments
List<PermissionSetAssignment> listOfNewPermAssign = new List<PermissionSetAssignment>();
for(PermissionSetAssignment permAssign : listOfPermissionSetAssignments){
PermissionSetAssignment newPermSetAssign = new PermissionSetAssignment();
newPermSetAssign.PermissionSetId = newPermSetId;
newPermSetAssign.AssigneeId = permAssign.AssigneeId;
listOfNewPermAssign.add(newPermSetAssign);
}
insert listOfNewPermAssign;
Leave a comment!
Subscribe
0 Comments