In Salesforce, when there’s a lot of business logic involved that would determine which records will be shared with the Users, Apex Sharing is the way to go.
Share Object
First, it’s important to understand that every object that’s private in the Org Wide Defaults has a Share Object associated with it.
For instance, Account has a share object as Account__Share.
One more important thing to note is that there’s no share object for the detail part of the relationship as it is controlled by the Parent Object.
Sharing Records
To share a particular record in Salesforce, you first need to create its share record through Apex and insert that record into the database.
For example, let’s take the example of sharing an Account Record to understand it better.
Syntax:
Account__Share accShare = new Account__Share();
// Set the record Id which needs to be shared.
accShare.ParentId = recordId;
// Set the ID of the user or group being granted access.
accShare.UserOrGroupId = userOrGroupId;
// Set the access level.
accShare.AccessLevel = ‘Read’;
// Set rowCause to ‘manual’ for manual sharing.
// This line can be omitted as ‘manual’ is the default value for sharing objects.
accShare.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(accShare,false);
Code Peek
The above code does three major things that help Salesforce decide how access needs to be given for a record.
- ParentId – What record to share
- UserId/GroupId – Who can see the record after sharing
- Access Level – What access the user will have
Conclusion
As mentioned above, if you’re sharing records using Apex for a complex business use case for example you need to make a callout to ensure you are sharing a correct record then you can use Apex sharing. For normal circumstances, always try to use Sharing Rules of Salesforce.
Learn more about Apex with my related articles below!
Additional Resources:
- Salesforce Dynamic Apex
- Ways to Deserialize Apex
- Apex Unit Testing
- Apex Developer Guide: Sharing a Record Using Apex
Cover Photo by Markus Winkler on Unsplash