0

I am trying to bulkify the soql to retrieve fieldPermissions for a set of users. The following query returns the field permission for a single user:

SELECT  SobjectType, Field FROM FieldPermissions WHERE (ParentId IN (SELECT PermissionSetId FROM PermissionSetAssignment WHERE Assignee.Id =:userId)) AND (PermissionsRead = true) AND SobjectType IN :objectNames AND Field IN :fieldNames.

I tried using a IN operator BUT it doesn't return which user the permissions belong to. I have tried different options of the retrieving it via the permission set assignment but it failed.

Any help would be appreciated.

1 Answer 1

0

You can use the following code:

FieldPermissions fieldPermissions = [SELECT ParentId, SobjectType, Field FROM FieldPermissions WHERE (PermissionsRead = true) AND SobjectType IN :objectNames AND Field IN :fieldNames];
Set<Id> parentIds = new Set<Id>();
for(fp : fieldPermissions)
    parentIds.add(fp.ParentId);

PermissionSetAssignment permissionSetIds = [SELECT PermissionSetId, Assignee.Id FROM PermissionSetAssignment WHERE Assignee.Id IN :userIds AND PermissionSetId IN :parentIds];

Map<Id, Set<Id>> mapUsersToPermissionIds = new Map<Id, Set<Id>>;
for(psi : permissionSetIds){
    if(!mapUsersToPermissionIds.containsKey(psi.PermissionSetId))
        mapUsersToPermissionIds.put(psi.PermissionSetId, new Set<Id>());
    mapUsersToPermissionIds.get(psi.PermissionSetId).add(psi.Assignee.Id);
}

We now first retrieve all FieldPermissions according to your conditions. Then we make a Set of parentIds (Permission Set Ids) that the fields are related to. Next, we retrieve all users in userIds (make sure this variable is set) which have one or more of the permission sets we retrieved earlier. Lastly, we map the users to the permission set ids. You can now use the mapUsersToPermissionIds map to retrieve a Set of users which have the permission set.

Example:

for(fp : fieldPermissions)
    System.debug('Set of users for ' + fp.Field + ': ' + mapUsersToFieldPermissions.get(fp.ParentId));

Is this a viable solution to your problem?

Keep in mind that I typed this code in a textbox, let me know if it returns any errors!

0

You must log in to answer this question.

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