Sub topic 15
Creating shares programmatically with Apex
This chapter assumes you know the share table fields from the previous chapter (ParentId, UserOrGroupId, AccessLevel, RowCause) and can write basic Apex and SOQL.
When to use Apex sharing
Sharing rules and teams cover most needs. Use Apex when the rule depends on logic that criteria cannot express, such as a lookup on a related record or an integration event. Apex sharing means inserting rows into an object's share table, for example Invoice__Share.
Manual versus Apex sharing reasons
The row cause decides how long a share lasts.
| Row cause | Created by | Survives owner change |
|---|---|---|
| Manual | Sharing button or code using the Manual cause | No, removed |
| Apex sharing reason (custom) | Apex code that uses your reason | Yes |
A share with the Manual cause disappears when the record owner changes. For logic-driven access that must last, define an Apex sharing reason on the custom object. Go to the object's Apex Sharing Reasons related list and create one named Finance_Review. Salesforce exposes it as Finance_Review__c.
A reusable helper
This class shares an invoice with a user and uses the custom reason.
public with sharing class InvoiceSharing {
public static Boolean shareInvoice(Id invoiceId, Id userId) {
Invoice__Share share = new Invoice__Share();
share.ParentId = invoiceId;
share.UserOrGroupId = userId;
share.AccessLevel = 'Read';
share.RowCause = Schema.Invoice__Share.RowCause.Finance_Review__c;
Database.SaveResult result = Database.insert(share, false);
if (!result.isSuccess()) {
Database.Error err = result.getErrors()[0];
// A duplicate share is not a real failure.
if (err.getStatusCode() == StatusCode.FIELD_INTEGRITY_EXCEPTION) {
return true;
}
System.debug(LoggingLevel.ERROR, err.getMessage());
return false;
}
return true;
}
}Passing false as the second argument makes Database.insert report errors in the result instead of throwing. This lets a bulk job continue past a single bad row.
Rules that cause errors
- The share table exists only when the object's org-wide default is Private or Public Read Only. With Public Read/Write there is nothing to add.
AccessLevelcan only widen access. You cannot grant less than the default, and you cannot grant Owner.- The running user must be able to share the record. That means the owner, a user above the owner in the role hierarchy, or a user with Modify All Data. Otherwise the insert fails with
INSUFFICIENT_ACCESS. - Changing the org-wide default to Public Read/Write deletes the Apex shares. Changing it back does not restore them.
- Standard objects use their own share objects, such as
AccountSharewithAccountId, and accept only the Manual cause from code.
Removing and verifying shares
To revoke access, query the share rows by ParentId and RowCause, then delete them. Never delete rows whose cause is Owner, a sharing rule, or a team. Salesforce manages those, and recalculation recreates them.
After the insert, confirm the result with the Invoice__Share query from the previous chapter. Check that the row shows your custom reason.
Exercise
A trigger shares each invoice with its approver using RowCause Manual. After a bulk owner reassignment, approvers lose access. Why, and what is the fix?
Show answer
Manual shares are deleted when the record owner changes. Create an Apex sharing reason on Invoice_c, such as FinanceReview, and set RowCause to Schema.Invoice_Share.RowCause.FinanceReview__c. Shares with that cause survive owner changes.