2

So I'm trying to create a function that allows you to create a sharing rule through Apex with any Object. Is there a way to generalize this so I don't have repeating code? From what I understand the sharing object is the name of your SObject with '__Share'. So my method would be customShareMapping(String apiName, String shareWith, String accessLevel);

Is there a way to achieve this?

1 Answer 1

2

That logic only applies to custom object sharing, and only if the object isn't public read/write. Standard sharing uses various specialized tables, such as AccountShare or CaseShare (to name a couple). A full solution would involve some heavy lifting, and probably wouldn't be worth it. However, let's say you wanted to approach it, your algorithm would be something like:

  • Describe the object (apiName), and see if isCustom() is true or not.
  • If not custom, consult a mapping table to determine which share table to use.
  • If custom, append __Share to the apiName to determine which share table to use.
  • Try to describe the share table resolved above.
  • If not custom, and table exists, use some specialized handler to determine which fields to set.
  • If custom, able table exists, use generic algorithm to create shares (they all work the same).

You may also need/want a "share reason" parameter. Standard shares can only be "manual", but custom shares might include custom sharing reasons.

2
  • This is exactly what I was looking for! Thank you. A quick question on the Standard sharing - do all Standard objects support this? If not, would the said (apiName + 'Share') object error out? Also, is this possible for Master Detail objects? For a Master Detail would you have to find the parent object and perform the Share on that? Commented Mar 30, 2015 at 14:10
  • Not all objects have a share (and some only when settings are appropriate). Master-detail objects mean you'd have to find the parent, either by iterating through all fields, describing, and figuring out which one to use. To figure out the existence of a table, use Schema.getGlobalDescribe().
    – sfdcfox
    Commented Mar 30, 2015 at 14:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .