With Sharing keyword for Restriction Rule in Salesforce

With Sharing keyword for Restriction Rule in Salesforce

If “With Sharing” keyword is used in the Apex Class, then the SOQL won’t run in System Mode. It will run in User Mode and respect the Restriction Rules configured.

Custom Field in User Object for User Criteria:

Custom Field in the Custom Object for Record Criteria:

Restriction Rule on the Custom Object:

Sample Code:

Visualforce Page:

<apex:page controller="EmployeesDataController">
    <apex:pageBlock>
        <apex:pageBlockTable value="{!listEmployees}" var="emp">
            <apex:column>{!emp.Name}</apex:column>
            <apex:column>{!emp.Age__c}</apex:column>
            <apex:column>{!emp.Above_18__c}</apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Apex Class:

public with sharing class EmployeesDataController {
    
    public List < Employee__c > listEmployees { get; set; }
    
    public EmployeesDataController() {
        
        listEmployees = new List < Employee__c >();
        listEmployees = [ SELECT Id, Name, Age__c, Above_18__c FROM Employee__c LIMIT 100 ];
        
    }

}

Output:

Note:

If”with sharing” keyword is removed, the SOQL will run in System Mode and return all the data. It won’t obey the Restriction Rule.

Leave a Reply