In Force.com platform there are different level to control the access of the data. In this blog I will explain you how extend the records access(Sharing the record) to users or group through apex code.
1. Create an object called 'Expense' with all the default settings.
2. Create a custom object tab for Expense object.
3. Make the 'Expense' object as private in the security control under the setup area.
If an object is 'private' under the 'Security control' then user have access to the object records which created by him self. Once you made this change 'Sharing' button will be added into the Expense page layout. By using this Sharing button you can able to view the record access which means who have access to that records. Along with this 'Expense__Share' object will be created for 'Expense__c' by Salesforce. It will not be available in the object list in the setup area. By using this share object only we will share the expense record.
From above screen showing that 'Petrol' expense record can accessed only by 'Saravana Selvaraj'. You can also see the access level and the explanation is below in that screen. By using 'Add' button you can grant the access to user or group but our goal is to share the record through apex code. In the below code I am sharing the petrol record to the user called 'Robin S'. Execute the below code in your developer console.
Expense__Share expenseShareIns=new Expense__Share(AccessLevel='Edit',UserOrGroupId='00528000001vZ7h',ParentID='a012800000HSmCg',RowCause='Manual'); insert expenseShareIns;
I have Below is the output
Now 'Robin S' can able to access this petrol record.
I hope you find this article interesting, Rate this article if its useful to you.
Let me know your suggestions in comment section.