About Apex Sharing Reason

Apex sharing reason is used to identify, why the record are shared with the user. If a developer is doing any operation on that record sharing then he can able identify in which sharing records he needs to do the operation. Its especially for managing a record sharing through apex code.Lets go through this with some example.

Records level access:

If an object is 'private' under the 'Security control' then user, have access to the object records which is created by him self. If you want others to access the records you need to share the records with that users.

Scenario:

1. Create an object called 'Expense' with all the default settings.

2. Create a custom lookup field to user called 'Manager' .

3. Create a custom object tab for Expense object.

4. Make the 'Expense' object as private in the security control under the setup area.

In my org I have a user called Smith. He is a account head and he might be the manager for some user. If any expense records is created by an user then that record should shared with his manager(may be Smith or some one else) and the account head Smith.Suppose Bob is creating a expense record called 'Petrol' by selecting manager as Smith then the petrol record should be shared with Smith twice. But you can't share it twice. To achieve this you should have two different sharing reason.

Create apex sharing reason:

1. Go to Expense object from setup objects.

2. Go to apex sharing reason related list and click the new button

3. Enter reason label as 'Manager' and reason name will be auto populated. Created one more and name it as 'Account manager'. it will look like below screen.

Now through apex code or even manually you can able share the petrol record with Smith twice with different reason. Below is the code to share the record with user. Click here to know more about sharing a record through apex code.

list<Expense__Share> expenseShareList=list<Expense__Share>();
expenseShareList.add(new Expense__Share(AccessLevel='Edit',UserOrGroupId='00528000001vZ7h',ParentID='a012800000HSmCg',RowCause='Manager__c'));
expenseShareList.add(new Expense__Share(AccessLevel='Edit',UserOrGroupId='00528000001vZ7h',ParentID='a012800000HSmCg',RowCause='Account_manager__c'));
insert expenseShareList;

in the above code for parentID I have hard coded the Smith user id. But you have to pass the manager id from the expense record and Smith user id by querying from user. The out put will look like below screen.

I hope you find this article interesting, Rate this article if its useful to you.

Let me know your suggestions in comment section.

Rating: 
No votes yet