We can control access to data at many different levels (OWD, Sharing Rule, Role Hierarchies) in salesforce. However, in which case we need to use apex managed sharing? Can you please explain with examples.
A simple use case which comes to my mind could be as follows:
At an organization, HR person conducts the interviews of candidates. HR person wants to share candidate's profile to an Interviewer.
Consider, OWD of Candidate object is Private.
Here, you can think that HR person would always create candidate record and in the candidate object, a Lookup field can be used to store Interviewer.
So, in the beginning no other person can see candidate information. When HR person selects the Interviewer (User) from the Lookup and saves the record then that record will be visible to Interviewer to take interview of the Candidate.
During sharing record creation following needs to be specified:
- objectNameAccessLevel - (Read, Edit or All) and for the above use case it will be
- ParentID - This will be Candidate Record Id
- RowCause - For purpose of interview
- UserOrGroupId - Interviewer Id (user)
For more information, refer Sharing a Record Using Apex