Write a trigger to share a custom object record (Project__c) using Apex Managed Sharing (Project__Share) when a Manager__c lookup field is populated or updated.
Answer
Create Project__Share records with a custom Apex sharing reason. Requires the object's OWD to be Private or Public Read Only.
apex
trigger ProjectTrigger on Project__c (after insert, after update) {
List<Project__Share> shares = new List<Project__Share>();
Set<Id> changedIds = new Set<Id>();
for (Project__c p : Trigger.new) {
Id oldMgr = Trigger.isUpdate ? Trigger.oldMap.get(p.Id).Manager__c : null;
if (p.Manager__c != oldMgr) {
changedIds.add(p.Id);
if (p.Manager__c != null) {
shares.add(new Project__Share(ParentId = p.Id, UserOrGroupId = p.Manager__c,
AccessLevel = 'Edit', RowCause = Schema.Project__Share.RowCause.Manager__c));
}
}
}
// remove stale Apex shares first
delete [SELECT Id FROM Project__Share WHERE ParentId IN :changedIds
AND RowCause = :Schema.Project__Share.RowCause.Manager__c];
insert shares;
}
Only Apex Sharing Reasons (not 'Manual') survive owner changes, and the Manager__c must be a User Id.
apex-triggertriggercodingscenariosharing