Are there any solutions that allow assigning Custom permission to Profiles using apex? I know about the object SetupEntityAccess. But it is for linking Custom Permission and Permission Set. But I want to avoid using the Permission Set

  • 2
    IMHO you really need to embrace Permission Sets and Permission Set Groups; Salesforce is on a journey to deprecate Profiles so the sooner you switch the sooner you get that transition out of the way, before you implement additional things like this that will make the transition harder for you.
    – Phil W
    Commented Jan 5, 2023 at 8:11

2 Answers 2


Hope you are doing well, using Apex you can assign permission set to any user. Only we need that permission set 'Id' and the 'Id' of the User to be assigned.

/* Get the Id of the permission Set using Permission Set Name */

PermissionSetAssignment psa = [SELECT PermissionSetId, AssigneeId FROM 
                               PermissionSetAssignment WHERE 
                               PermissionSet.Name = 'permissionSetName'].Id;

/* Now you need to assign that permission set to the user, So first get the User using SOQL*/

List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
for (User u : [SELECT Id, UserRole.Name,Profile.Name, IsActive FROM User WHERE  UserRole.Name LIKE '%UserRoleName%' AND Profile.Name Like '%UserProfileName%' AND IsActive = true])
    PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = psa , AssigneeId = u.Id);
    upsert permissionSetList;
}catch(exception e){
    system.debug('exception caught' + e);

I hope you got you answer, if not feel free to ask.

  • 1
    This doesn't really answer the original question which stated they wanted to avoid permission sets. Additionally the existing answer already covers permission set assignments that are more aligned to the original question than this so I can't upvote what you have here.
    – Phil W
    Commented Jan 5, 2023 at 12:23
  • Custom Permission cannot be assigned to the user directly. That could be done by means of assigning Permission Set to the user. Custom Permission should already be assigned to the Permission Set or assigning Custom Permission to the profile. Assigning Custom Permission to a Profile or Permission Set can be done via salesforce UI, or via Metadata API. Take a look at : help.salesforce.com/s/… and help.salesforce.com/s/… Commented Jan 5, 2023 at 12:30
  • 1
    You misunderstand me; the other answer already covers permission set usage (and I am aware of what can and cannot be done with custom permission assignment and Apex). I don't understand why you added this answer when the other answer already covers assigning a permission set (with the custom permission) to all users with a given profile.
    – Phil W
    Commented Jan 5, 2023 at 12:36
  • Thanks for your answers. But @PhilW is right. The original question was about how to avoid permission-set usage. We can do this manually. I mean edit Profile and add Custom Permission. I guess the solution via apex that I need doesn't exist
    – Vadym
    Commented Jan 5, 2023 at 22:57

I have a solution which will help you out.

Via Metadata Api using the library from FinancialForce, you can get it at - https://github.com/financialforcedev/apex-mdapi/tree/master/apex-mdapi/src/classes All you need to do is copy the MetadataService class and save it into your org.

once done add the below method to your Apex class-

public class MetadataServiceExamples {
    public static void updateProfileCustomPermission()
        MetadataService.MetadataPort service = createService();
        MetadataService.IReadResult readResult =        
            service.readMetadata('Profile', new String[] { 'Gold Partner User' }); // profile name
        MetadataService.Metadata[] records = readResult.getRecords();
        MetadataService.Profile prfile =  new MetadataService.Profile();
        prfile.fullName = 'Gold Partner User';
        prfile.custom = false;
        MetadataService.ProfileCustomPermissions profileCustomPermission = new MetadataService.ProfileCustomPermissions();
        profileCustomPermission.name = 'StackExchange';// custom permission name
        profileCustomPermission.enabled = true;
        prfile.customPermissions  = new MetadataService.ProfileCustomPermissions[] {profileCustomPermission} ;
            List<MetadataService.SaveResult> results =
                new MetadataService.Metadata[] { prfile });
    public static MetadataService.MetadataPort createService()
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        return service;     
    public static void handleSaveResults(MetadataService.SaveResult saveResult)
        // Nothing to see?
        if(saveResult==null || saveResult.success)
        // Construct error message and throw an exception
            List<String> messages = new List<String>();
                (saveResult.errors.size()==1 ? 'Error ' : 'Errors ') +
                'occured processing component ' + saveResult.fullName + '.');
            for(MetadataService.Error error : saveResult.errors)
                    error.message + ' (' + error.statusCode + ').' +
                    ( error.fields!=null && error.fields.size()>0 ?
                     ' Fields ' + String.join(error.fields, ',') + '.' : '' ) );
                System.debug(' message '+messages);
            //throw new MetadataServiceExamplesException(String.join(messages, ' '));
            System.debug(' failure ');
        //throw new MetadataServiceExamplesException('Request failed with no specified error.');
  • Doesn't quite answer the question, though what you provided is valuable. Could you edit the answer to give a bit more info as to why you would take this approach, not just show the code?
    – Phil W
    Commented Jan 5, 2023 at 8:13
  • What you can do is create a permission set which has the custom permissions that you want to give to a user. And by following the above code you can just assign the permission set to the user which will give them the desired access. Commented Jan 5, 2023 at 10:07
  • Please edit the answer to provide these details.
    – Phil W
    Commented Jan 5, 2023 at 12:21
  • @Vadym Please go through the updated answer. Commented Jan 9, 2023 at 9:37
  • Never just add the MetadataService class; make sure to also add the related unit tests to keep your code coverage up.
    – Phil W
    Commented Jan 9, 2023 at 10:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .