function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Soumya BeheraSoumya Behera 

Permission assignment through apex code

Hi Fokes,

I have an requirment where i need to assgin an permission based on the some codition. So can it be possible through code to assign permission set to the user. 
Need to do by Apex coding. Please guide .
Regards,
Ranjan
Best Answer chosen by Soumya Behera
KaranrajKaranraj
Hi Ranjan - Yes you can able to assign permission set to user through apex code
PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = myPermissionSetId, AssigneeId = myAssigneeId);
insert psa;
myPermissionSetId - Pass the Id of the permission set
myAssigneeId - User Id to whom you want to assign the permission set

You can write SOQL query to get the permission set Id in your apex class - https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_permissionset.htm

 

All Answers

KaranrajKaranraj
Hi Ranjan - Yes you can able to assign permission set to user through apex code
PermissionSetAssignment psa = new PermissionSetAssignment(PermissionSetId = myPermissionSetId, AssigneeId = myAssigneeId);
insert psa;
myPermissionSetId - Pass the Id of the permission set
myAssigneeId - User Id to whom you want to assign the permission set

You can write SOQL query to get the permission set Id in your apex class - https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_permissionset.htm

 
This was selected as the best answer
Soumya BeheraSoumya Behera
Thanks Karanraj for the quick reply. It really helped.