Play Games

Search This Blog

Wednesday, May 1, 2024

How to enforce field level security in SOQL Query salesforce - Salesforce Globe 4U

Solution: There are 2 ways to enforce FLS in SOQL query

1)Using USER_MODE 

2)WITH SECURITY_ENFORCED clause

Using USER_MODE:

Example: run the below code in execute anonymous window 

List<Account> lstAccount = new List<Account>();

lstAccount = [Select id,name from Account with USER_MODE];

system.debug('No of Accounts: '+lstAccount.size());

SELECT Id,name from Account with USER_MODE

Output:



Using WITH SECURITY_ENFORCED clause:

Example: run the below code in execute anonymous window 

List<Account> lstAccount = new List<Account>();

lstAccount = [Select id,name from Account with SECURITY_ENFORCED];

system.debug('No of Accounts: '+lstAccount.size());


Note: Salesforce recommends using the USER_MODE than WITH SECURITY_ENFORCED as it has additional advantages

1) USER_MODE accounts for polymorphic fields as well where as SECURITY_ENFORCED donot account for it.

2)USER_MODE returns all the FLS errors where as SECURITY_ENFORCED returns only the first.

Refer to the salesforce link for more details

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_enforce_usermode.htm

How to query the validation rules of an object in salesforce - Salesforce Globe 4u

Solution: Using tooling api ,the validation rules can be queried.

Example: Use the following query in developer console by enabling the tooling api

SELECT Id, Active, Description, EntityDefinition.QualifiedApiName, ErrorDisplayField, ErrorMessage,ValidationName FROM ValidationRule

Output:



To filter validation rules for a specific object, use EntityDefinition.QualifiedApiName(object api name) in where clause of query 

Example:

SELECT Id, Active, Description, EntityDefinition.QualifiedApiName, ErrorDisplayField, ErrorMessage,ValidationName FROM ValidationRule where EntityDefinition.QualifiedAPiName='A__c'

Output: