I have to prepare a batch class to list down users who has access a field.
As example : Opportunity has a field say (Tax_id__c). Now I want to execute SQOL / or any API to identify number of users who can access to Tax_id__c.
Please suggest.
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityadded
Whether its custom or standard field you can get the FieldDefinitionId
from UserFieldAccess object and then create durable ids by concatenating user ids as shown below:
String fieldId = [
SELECT FieldDefinitionId FROM UserFieldAccess
WHERE FieldDefinition.EntityDefinition.QualifiedApiName='Opportunity'
AND FieldDefinition.QualifiedApiName='Tax_id__c'
AND User.Id=:UserInfo.getUserId()
].FieldDefinitionId; // Using UserInfo.getUserId() only to get FieldDefinitionId which will be constant in given org
List<String> durIds = new List<String>();
// Use for loop of User Ids to create the list
durIds.add(fieldId+'.0050K000008pGrkQAE'); // add UserId 1
durIds.add(fieldId+'.0050K000008BZTYQA4'); // add User Id 2
System.debug([SELECT Id, UserId, User.Name, IsUpdatable, IsCreatable, IsAccessible, EntityDefinitionId, FieldDefinitionId
FROM UserFieldAccess
WHERE DurableId IN :durIds]);
You can get it from UserFieldAccess
object. You should give DurableId
in the form of Object.Field.UserId as shown below.
SELECT Id, UserId, User.Name, IsUpdatable, IsCreatable, IsAccessible, EntityDefinitionId, FieldDefinitionId FROM UserFieldAccess WHERE DurableId IN ('Account.Name.0050K000008pGrkQAE', 'Account.Name.0050K000008BZTYQA4')
Collect all User Ids and create comma separated list in form of Opportunity.Tax_id__c.*UserId1*,Opportunity.Tax_id__c.*UserId2*, Opportunity.Tax_id__c.*UserId3*....
You can use isAccessible() for checking user has access or not. Below example checks if the user has read access on the Contact.Name field
if (!Schema.sObjectType.Contact.fields.Name.isAccessible()){
return '';
}
Below example checks if the user has update access on the Contact.Name field
if (!Schema.sObjectType.Contact.fields.Status__c.isUpdateable()){
return null;
}
Please refer page https://developer.salesforce.com/page/Enforcing_CRUD_and_FLS