How to change field permissions in a permission set or profile programmatically (APEX)

  • Salesforce provides an object FieldPermissions where field’s permission is stored for a permission set.
  • Programmatically it’s only possible for Permission Set not for Profile.
  • Here is Salesforce help article: https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_fieldpermissions.htm
  • TIP: while providing field name, we need to pass full name of API Name along with <object_api_name>.<namespace_prefix><field_api_name>
 public static void addToPermissionSet(String fieldName){
        String fieldAPIName = assertFieldName(fieldName, true); 
        PermissionSet ps = [SELECT Id,Name FROM PermissionSet WHERE Name = 'Example' LIMIT 1];
        String fullAPIName = 'User.'+fieldAPIName; /* Example: User.TestMe__c */
        System.debug('FullAPI:' + fullAPIName);
        
        FieldPermissions newPerm = new FieldPermissions();
        newPerm.Field = fullAPIName;
        newPerm.ParentId = ps.Id;
        newPerm.PermissionsEdit = true;
        newPerm.PermissionsRead = true;
        newPerm.SobjectType = 'User';
        Insert newPerm; 
    }