Development questions
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.
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
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?