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:pageBlockTable value="{!listEmployees}" var="emp">

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 ];



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.

No comments:

Post a Comment