function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ForceRookieForceRookie 

Create Sharing Rules that user should only see records which he is the 'CreatedBy'

Help me to code it on APEX, the records should be visible to the user if the current user is the CreatedBy.

public class MyFilesSharingHandler {
	public void shareRecord(List<CustomObject__c> scope) {
		if (Trigger.isInsert) {
			
			List<CustomObject__Share> shareLst = new List<CustomObject__Share>();
			for (CustomObject__c c : scope) {
				CustomObject__Share share = new CustomObject__Share();
				share.AccessLevel = 'Read';
				share.ParentId = c.Id;
				share.UserOrGroupId = c.CreatedById;
				shareLst.add(share);
			}
			if (!shareLst.isEmpty()) {
				insert shareLst;
			}
		}
	}
}
Best Answer chosen by ForceRookie
ForceRookieForceRookie

I update it to this..

public class MyFilesSharingHandler {
	public void shareRecord(List<CustomObject__c> scope) {
		if (Trigger.isUpdate) {
			
			List<CustomObject__Share> shareLst = new List<CustomObject__Share>();
			for (CustomObject__c c : scope) {
                            if (c.OwnerId != c.CreatedById) {
				CustomObject__Share share = new CustomObject__Share();
				share.AccessLevel = 'Read';
				share.ParentId = c.Id;
				share.UserOrGroupId = c.CreatedById;
				shareLst.add(share);
                            }
			}
			if (!shareLst.isEmpty()) {
				Database.SaveResult[] dsr = Database.insert(shareLst,false);
			}
		}
	}
}

Do you think it will work on After Update? And not getting an error when I change/update the Owner?

All Answers

Dayakar.DDayakar.D
Hi Rookie,

We can use with sharing  keyword for enforcing the sharing rules, by default Apex code will run in system context where Apex code will have access to all the objects, files, if we didn't mention anything in the class, code will run in system context where sharing rules aren't applied.
if you want to enforce sharing rules we need to explicitly mention with sharing keyword in your class declaration.

below is the link which will explain in detail about with and without sharing keyword.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_keywords_sharing.htm 

Note: Make sure the object OWD is private.

Please let me know, if you need more info.

Best Regards,
Dayakar.D
ForceRookieForceRookie

I'm getting this error in my code -- "insufficient access rights on cross-reference id"

Can you help me with it?

Dayakar.DDayakar.D
Rookie,  You no need to write that logic to share the reocrd with created by user, we can use OWD settings for restrict record acess to only owner of the record.
In the code you are trying to share the record with owner of the record only, which doesn't make sense.

please follow the below steps to make your object private, which will restrict access to only owner of the record.

goto Setup -- > Security controlls  ---> sharing settings  ---> click on Edit button on sharing settings page.---- > search for your object and select private in default internal access drop down.

Best Regards,
Dayakar.D

 
ForceRookieForceRookie

But I need to. If the Owner was changed, the CreatedBy should still have an access to the record.

Is this right?

public class MyFilesSharingHandler {
	public void shareRecord(List<CustomObject__c> scope) {
		if (Trigger.isUpdate) {
			
			List<CustomObject__Share> shareLst = new List<CustomObject__Share>();
			for (CustomObject__c c : scope) {
				CustomObject__Share share = new CustomObject__Share();
				share.AccessLevel = 'Read';
				share.ParentId = c.Id;
				share.UserOrGroupId = c.CreatedById;
				shareLst.add(share);
			}
			if (!shareLst.isEmpty()) {
				Database.SaveResult[] dsr = Database.insert(shareLst,false);
			}
		}
	}
}
Dayakar.DDayakar.D
Yes correct, the updated code will work.

Best Regards,
Dayakar.D
ForceRookieForceRookie

I update it to this..

public class MyFilesSharingHandler {
	public void shareRecord(List<CustomObject__c> scope) {
		if (Trigger.isUpdate) {
			
			List<CustomObject__Share> shareLst = new List<CustomObject__Share>();
			for (CustomObject__c c : scope) {
                            if (c.OwnerId != c.CreatedById) {
				CustomObject__Share share = new CustomObject__Share();
				share.AccessLevel = 'Read';
				share.ParentId = c.Id;
				share.UserOrGroupId = c.CreatedById;
				shareLst.add(share);
                            }
			}
			if (!shareLst.isEmpty()) {
				Database.SaveResult[] dsr = Database.insert(shareLst,false);
			}
		}
	}
}

Do you think it will work on After Update? And not getting an error when I change/update the Owner?
This was selected as the best answer
Dayakar.DDayakar.D
Yes if it system admin, you won't get any error, as by default system admin will have View all data permission at profile level.
If the user is not system admin, then either the User profile is having view all data permission in profile or view all permission at object level.
Please check once.

Best  Regards,
Dayakar.D
ForceRookieForceRookie
Thank you Dayakar!
Frenix RajiahFrenix Rajiah
I had written this trigger for a custom object called incident that works well. The only limitation is that, Apex Managed Sharing only works with internal users and customer community plus license users, Apex sharing is not available for Customer Community users.
trigger IncidentTrigger on Incident__c (after update) {
         List<Incident__c> scope = new list<Incident__c>(Trigger.new);
         List<Incident__Share> shareLst = new List<Incident__Share>();
         for (Incident__c c : scope) {
                     if (c.OwnerId != c.CreatedById) {
                         Incident__Share share = new Incident__Share();
                         share.AccessLevel = 'Read';
                         share.ParentId = c.Id;
                         share.UserOrGroupId = c.CreatedById;
                         shareLst.add(share);
                            }
            }
if (!shareLst.isEmpty()) {
                Database.SaveResult[] dsr = Database.insert(shareLst,false);
     }
}

Some links supporting the above limitation of using Apex Managed Sharing for Customer Community users> 
https://developer.salesforce.com/forums/?id=9060G000000Xb88QAC
https://developer.salesforce.com/forums/?id=906F000000090lUIAQ