Sub topic 15
Creating shares programmatically with Apex
Sharing rules, manual shares, and teams cover most access requirements. Sometimes the logic is too specific for them, such as "share each invoice with the user named in a lookup field". Apex managed sharing handles those cases by writing share rows directly.
This chapter assumes you know how share objects and row causes work (the previous chapter), can read basic Apex and SOQL, and understand how org-wide defaults decide whether a share table exists.
What Apex sharing does
Every object with a private or read-only baseline has a share object. Inserting a row into it grants a user or group access to one record. Apex sharing is code that inserts, updates, and deletes those rows.
The naming follows a pattern:
| Object type | Share object | Parent field |
|---|---|---|
| Custom object `Invoice__c` | `Invoice__Share` | `ParentId` |
| Standard object `Account` | `AccountShare` | `AccountId` |
| Standard object `Opportunity` | `OpportunityShare` | `OpportunityId` |
The fields you set are the same for all of them:
- The parent record Id.
UserOrGroupId: a user, public group, role, or role and subordinates group.AccessLevel:ReadorEdit. Standard objects also acceptAllin some cases, but you cannot grantAllon a custom object.RowCause: why the row exists.
A share table does not exist for objects whose org-wide default is Public Read/Write. There is nothing to grant, so the share object is not available for that object.
Row causes decide how long a share lives
The row cause controls what happens to a share when something changes. This is the main design choice in Apex sharing.
| Row cause | Created by | Survives an owner change? | Removed by recalculation? |
|---|---|---|---|
| `Manual` | The Sharing button, or Apex using the Manual cause | No, removed | No |
| Apex sharing reason (custom objects only) | Apex | Yes | No, kept |
| Rule, Team, Owner, and similar | The platform | Managed by the platform | Rebuilt by the platform |
Using Manual from code is the equivalent of a user clicking Sharing. It is simple, but Salesforce deletes those rows when the record owner changes. For access that must outlive ownership changes, define an Apex sharing reason.
To create one:
- Open the custom object in Setup.
- Find Apex Sharing Reasons and click New.
- Enter a label and a name, for example
Finance_Review.
Salesforce exposes it in code as Schema.Invoice__Share.RowCause.Finance_Review__c. Apex sharing reasons exist only for custom objects. For standard objects, Apex can only create shares with the Manual row cause.
Granting access in bulk
The spine's basic example inserts one share and reports a failure without throwing:
Invoice__Share share = new Invoice__Share();
share.ParentId = invoiceId;
share.UserOrGroupId = userId;
share.AccessLevel = 'Read';
share.RowCause = Schema.Invoice__Share.RowCause.Manual;
Database.SaveResult result = Database.insert(share, false);
if (!result.isSuccess()) {
System.debug(result.getErrors()[0].getMessage());
}The second argument, false, turns on partial success. One bad row does not roll back the others, and you read each failure from the result.
In real code, triggers and batch jobs handle many records at once. This class builds all the share rows first, then runs one DML statement:
public with sharing class InvoiceSharing {
public static void shareWithReviewers(Map<Id, Id> reviewerByInvoiceId) {
List<Invoice__Share> shares = new List<Invoice__Share>();
for (Id invoiceId : reviewerByInvoiceId.keySet()) {
Invoice__Share share = new Invoice__Share();
share.ParentId = invoiceId;
share.UserOrGroupId = reviewerByInvoiceId.get(invoiceId);
share.AccessLevel = 'Edit';
share.RowCause = Schema.Invoice__Share.RowCause.Finance_Review__c;
shares.add(share);
}
List<Database.SaveResult> results = Database.insert(shares, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
System.debug(LoggingLevel.ERROR,
'Share failed for ' + shares[i].ParentId + ': '
+ results[i].getErrors()[0].getMessage());
}
}
}
}This assumes the custom reason Finance_Review exists on Invoice__c. If you have not created it, the class does not compile.
Removing access
To revoke access, query the rows you created and delete them. Filter on the row cause so that you never touch the Owner row or shares from other mechanisms:
public static void removeReviewerShares(Set<Id> invoiceIds) {
List<Invoice__Share> toDelete = [
SELECT Id
FROM Invoice__Share
WHERE ParentId IN :invoiceIds
AND RowCause = :Schema.Invoice__Share.RowCause.Finance_Review__c
];
Database.delete(toDelete, false);
}The owner's Owner row cannot be deleted or edited, and the same is true of rows created by sharing rules and teams. Salesforce manages those.
Permissions and sharing mode
Changing share rows through Apex managed sharing requires the Modify All Data permission for the running user. A trigger that fires for a standard user will therefore fail when it tries to insert shares.
The usual fix is to run the sharing code in a context that has the permission, such as a class declared without sharing called from the trigger, or a batch job run by an administrator. Keep that class small and single-purpose. Apex that runs in system context can hide access bugs if it does more than the sharing work.
Common failures and edge cases
Partial-success results make these problems easy to miss, so read the error messages. The common ones:
- No share object. The object is Public Read/Write, or it is a detail object in a master-detail relationship. A detail record's access comes from its master, so it has no share table.
- Redundant share. You grant
Readto someone who already hasReador higher, for example through the role hierarchy or a rule. Salesforce rejects or ignores the row. This is not a bug in your code. - Wrong parent field. Standard share objects use
AccountId, notParentId. Mixing these up gives a compile error. - Invalid access level.
Allis not valid on a custom object share, andEditis invalid if the baseline grants more than your row would. - Row limits. Share inserts count toward DML statements and DML rows. Bulk them and avoid DML inside loops.
- Recalculation wipes manual-style rows. If the owner changes,
Manualshares disappear. Rebuild them from your own logic, or use an Apex sharing reason.
Recalculating Apex shares
Apex managed sharing rows with a custom reason survive owner changes. They are also kept during a full recalculation, but Salesforce does not recreate them if you change the logic. If your rule changes, for example a different group should now review overdue invoices, you must rebuild the rows yourself.
The standard approach is a batch class that implements Database.Batchable<SObject>. You can register it under the object's Apex Sharing Recalculation list in Setup. Salesforce runs it automatically after a full sharing recalculation. A recalculation class should delete the existing rows with your reason and re-insert the correct ones, so running it twice gives the same result.
Verifying your work
Query the share object to confirm the rows exist and have the cause you expect:
SELECT Id, ParentId, UserOrGroupId, AccessLevel, RowCause
FROM Invoice__Share
WHERE ParentId = '<invoice record Id>'In an Apex test, insert the parent and the share inside System.runAs with an administrator, then run the same query as an assertion. To test the effect on a real user, call System.runAs(user) and query Invoice__c for the record. The test should assert both that the user sees it with the share and that they cannot see it without.
When not to use Apex sharing
Apex sharing adds code to maintain, test, and recalculate. Use it only when declarative options cannot express the requirement. A criteria-based rule handles "share when Status is Overdue". An account team handles "share with these people on this account". Reach for Apex when the target of the share comes from data that rules cannot reference, such as a user lookup on the record, or an external system's assignment.
Exercise
A trigger on a standard user's save inserts an Invoice__Share row with the Manual row cause. The user then reassigns the invoice to a colleague, and the shared reviewer loses access. Name two changes that would fix both problems: the insert possibly failing for the standard user, and the reviewer losing access.
Show answer
First, create an Apex sharing reason on Invoice__c and use its row cause instead of Manual, because shares with an Apex sharing reason are kept when the owner changes while Manual shares are deleted. Second, run the share insert from a context that has Modify All Data, for example a small without sharing class or a batch job run by an administrator, because Apex managed sharing writes need that permission.
Exercise
You need to remove only the review access your code granted. Which WHERE conditions should the query on Invoice__Share use, and why?
Show answer
Filter on both ParentId IN :invoiceIds and RowCause = Schema.Invoice__Share.RowCause.Finance_Review__c. The row cause limits the delete to your own rows, so the Owner row and rows from sharing rules, teams, and manual shares are left alone.