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;

How to create a reusable field search Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable field search Lightning Component in Lightning Aura Components.

How to create a reusable field search Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable field search Lightning Component in Lightning Web Components.

How to create a reusable Lookup Lightning Component [Aura]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component in Lightning Aura Components.

How to create a reusable Lookup Lightning Component [LWC]

In this tutorial, I will show you how to create a reusable Lookup Lightning Component in Lightning Web Components.

How to remove Lightning App Page Header [Aura]

In this tutorial, I will show you how to remove Lightning App Page Header in Lightning Aura Components.

Leave a comment!

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments