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 Web Component

How to create a reusable field search Lightning Web ComponentIn this tutorial, I will show you how...

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 [LWC]

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

How to add or remove rows dynamically [LWC]

In this tutorial, I will show you how to add or remove rows dynamically in Lightning Web Components.

How to navigate through Lightning Components [LWC]

In this tutorial, I will show you how to navigate through Lightning Components in Lightning Web Components.

Leave a comment!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
devHamid