[SalesForce] Record sharing using lookup field criteria using apex (similar to controlled by parent)

We have a custom object that has a lookup to account (similar to Contact looking up to Account). We want the user who owns an account to see the records looking up to that account automatically without any user/admin intervention. The functionality would be similar to sharing setting "Controlled by parent". However, custom objects do not have this option. We want to replicate this option for custom object.

Other solution I have looked at is using criteria-based or owner-based sharing. However, that does not allow dynamic sharing (i.e., share with owner of the account) and is limited to sharing with previously described roles and groups, etc.

We want to make sure that the users can see the record as the new records are created with zero manual work. (e.g., Apex Trigger, Apex Class). This solution needs to be scalable with hundreds of thousands of records so manual sharing will not work and groups, roles, permissions sets may not be ideal.

Best Answer

"Controlled by parent" option is only available in Master-Detail relationship.

You can use Apex to share records. Every custom object has its Share object created by default; __Share. You only get the Share object created if OWD is Private/Read Only.

So if custom object name is Job, it will look like this:

List<Job__Share> jobShareList = new List<Job__Share>();
for(Job__c job : Trigger.new){
Job__Share jobShr  = new Job__Share();
// Set the ID of record being shared.
jobShr.ParentId = recordId;
// Set the ID of user or group being granted access.
jobShr.UserOrGroupId = userOrGroupId;
// Set the access level.Can be Edit, Read
jobShr.AccessLevel = 'Edit';
jobShr.RowCause = Schema.Job__Share.RowCause.Manual;
jobShareList.add(jobShr);
}

Database.SaveResult sr = Database.insert(jobShareList);

This will handle the records in bulk.