# 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.

**Topic:** Development · **Difficulty:** Hard · **Asked at:** Deloitte, Salesforce, PwC, EY · **Tags:** apex-trigger, trigger, coding, scenario, sharing

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-share-a-custom-object-record-project-c-using-apex-managed-sharing-project-share-when-a

## 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.

---
Source: ForceChallenges · last updated 2026-10-19
