SF Learners Hub

MASTER SALESFORCE, CONQUER YOUR GOALS

Record Sharing in Salesforce

Share This Post

What is Record Sharing in Salesforce and what are the different types of Record Sharing in Salesforce and How to do Share Records in Salesforce in different ways

Sharing enables record-level access control for all custom objects, as well as many standard objects (such as Account, Contact, Opportunity, and Case). Administrators first set an object’s organization-wide default sharing access level, and then grant additional access based on record ownership, the role hierarchy, sharing rules, and manual sharing. Developers can then use Apex-managed sharing to grant additional access programmatically with Apex.

Most sharing for a record is maintained in a related sharing object, similar to an access control list (ACL) found in other platforms.

Types of Sharing in Salesforce :

  • Record Ownership
  • Role Hierarchy
  • Sharing Rules
  • Manual Sharing.
  • Apex Sharing.

Record Ownership: Each record is owned by a user or optionally a queue for custom objects, cases and leads. The record owner is automatically granted Full Access, allowing them to view, edit, transfer, share, and delete the record.

Role Hierarchy: The role hierarchy enables users above another user in the hierarchy to have the same level of access to records owned by or shared with users. Users above a record owner in the role hierarchy are also implicitly granted Full Access to the record. The role hierarchy is not maintained by sharing records.

Sharing Rules: Sharing rules are used by administrators to automatically grant users within a given group or role access to records owned by a specific group of users.

Sharing rules can be based on record ownership or other criteria. You can’t use Apex to create criteria-based sharing rules. Also, criteria-based sharing cannot be tested using Apex.

Manual Sharing: User-managed sharing allows the record owner or any user with Full Access to a record to share the record with a user or group of users. This is generally done by an end user, for a single record. Only the record owner and users above the owner in the role hierarchy are granted Full Access to the record.

Users with the “Modify All” object-level permission for the given object or the “Modify All Data” permission can also manually share a record.

User-managed sharing is removed when the record owner changes.

Apex Sharing: Apex-managed sharing provides developers with the ability to support an application’s particular sharing requirements programmatically through Apex or the SOAP API. This type of sharing is similar to managed sharing.

Apex-managed sharing must use an Apex sharing reason. Apex sharing reasons are a way for developers to track why they shared a record with a user or group of users. Using multiple Apex sharing reasons simplifies the coding required to make updates and deletions of sharing records. They also enable developers to share with the same user or group multiple times using different reasons.

Apex Sharing Reason Field :

Property NameDescription
objectNameAccessLevelThe level of access that the specified user or group has been granted for a share sObject. The name of the property is AccessLevel appended to the object name.
For example, the property name for the LeadShare object is AccountShareAccessLevel. Valid values are: EditReadAll
Note: The All access level is an internal value and can’t be granted. This field must be set to an access level that is higher than the organization’s default access level for the parent object. For more information, see Understanding Sharing.
ParentIDThe ID of the object. This field cannot be updated.
RowCauseThe reason why the user or group is being granted access. The reason determines the type of sharing, which controls who can alter the sharing record. This field cannot be updated.
UserOrGroupIdThe user or group IDs to which you are granting access. A group can be :
A public group or a sharing group associated with a role. A territory group. This field cannot be updated.NoteYou can’t grant access to unauthenticated guest users using Apex.

How to Create Apex-Based Sharing :

public class JobSharing {
   
   public static boolean manualShareRead(Id recordId, Id userOrGroupId){
      // Create new sharing object for the custom object Job.
      Job__Share jobShr  = new Job__Share();
   
      // Set the ID of record being shared.
      jobShr.ParentId = recordId;
        
      // Set the ID of user or group being granted access.
      jobShr.UserOrGroupId = userOrGroupId;
        
      // Set the access level.
      jobShr.AccessLevel = 'Read';
        
      // Set rowCause to 'manual' for manual sharing.
      // This line can be omitted as 'manual' is the default value for sharing objects.
      jobShr.RowCause = Schema.Job__Share.RowCause.Manual;
        
      // Insert the sharing record and capture the save result. 
      // The false parameter allows for partial processing if multiple records passed 
      // into the operation.
      Database.SaveResult sr = Database.insert(jobShr,false);

      // Process the save results.
      if(sr.isSuccess()){
         // Indicates success
         return true;
      }
      else {
         // Get first save result error.
         Database.Error err = sr.getErrors()[0];
         
         // Check if the error is related to trival access level.
         // Access level must be more permissive than the object's default.
         // These sharing records are not required and thus an insert exception is acceptable. 
         if(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION  &&  
                  err.getMessage().contains('AccessLevel')){
            // Indicates success.
            return true;
         }
         else{
            // Indicates failure.
            return false;
         }
       }
   }
   
}

Using the with sharing, without sharing, and inherited sharing Keywords

Use the with-sharing or without-sharing keywords on a class to specify whether sharing rules must be enforced.

  • With Sharing: Use the with sharing keyword when declaring a class to enforce the sharing rules of the current user. Explicitly setting this keyword ensures that Apex code runs in the current user context. Apex code that is executed with the execute anonymous call and Connect in Apex always executes using the sharing rules of the current user.
public with sharing class sharingClass {

   // Code here

}
  • Without Sharing: Use the without sharing keyword when declaring a class to ensure that the sharing rules for the current user are not enforced.
public without sharing class sharingClass {

   // Code here

}

Follow Best Practices:

with sharingUse this mode as the default unless your use case requires otherwise.
without sharingUse this mode with caution. Ensure that you don’t inadvertently expose sensitive data that would normally be hidden by the sharing model. This sharing mechanism is best used to grant targeted elevation of sharing privileges to the current user.For example, use without sharing to allow community users to read records to which they wouldn’t otherwise have access.

Conclusion

I hope you like this blog and if you want any help let me know in the comment section.

Stay tuned, there is way more to come! Follow me on LinkedIn, Instagram, and Twitter. So you won’t miss out on all future articles.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Extract Valuable Data with Salesforce OCR

Revolutionize the way you handle and utilize your documents with OCR in Salesforce. Optical Character Recognition will enhance your data management and streamline business processes.