8

Is it possible to know, via apex code, if a certain object is Private, Public Read-Only or Public Read/Write?

3 Answers 3

6

For the Standard object, you can use Organization object to achieve this, query like,

Organization org = [Select Id, DefaultAccountAccess, DefaultContactAccess, DefaultLeadAccess, DefaultOpportunityAccess from Organization];

System.debug(org);

Query this object to obtain information about an organization's settings. Only one organization record exists per organization.

for the details, see the Organization object model documentation.

1
  • Thank you. That's what i'm looking for. I didn't know that object had these fields.
    – Ivo Rocha
    Jan 22, 2013 at 12:18
5

Another way to test for sharing of custom objects is to check the global describe Map.

Map<String, Schema.SObjectType> tokens = Schema.getGlobalDescribe();
if(tokens.containsKey('MyCustomObject__Share')) {
    //Share object exists, therefore custom object is private or public read only

    //Still need to use dynamic apex because this code won't compile if MyCustomObject__Share does not exist
    SObject share = tokens.get('MyCustomObject__Share').newSObject();
    share.put('ParentId', customObjectInstance.Id);
    share.put('UserOrGroupId', UserInfo.getUserId());
    //API Name of the Sharing reason, or don't populate if the reason is Manual
    share.put('RowCause', 'Sharing_Reason__c');
} else {
    //Share does not exist custom object is public read write
}

As you have already discovered, this is only for custom objects, @JiaHu's answer explains how to get the sharing level of a standard object.

4
  • If the MyCustomObject__Share object doesn't exist it enters the ELSE, but wouldn't it still cause an error if you reference MyCustomObject__Share inside your IF?
    – Phil B
    Jul 10, 2013 at 20:58
  • @Phil, it's only a string key in the global describe map, I'm not actually referencing the share objects describe information or token Jul 10, 2013 at 21:38
  • Ah sorry, I was assuming you'd have some references to the MyCustomObject__Share record inside the if statement (some type of logic assuming it passes the IF). Assuming that was the case wouldn't that cause an error?
    – Phil B
    Jul 11, 2013 at 13:11
  • @Phil, I updated the question with code for dynamically sharing a record Jul 11, 2013 at 23:31
0

Guess this should help you :

SELECT Id,ParentId,UserOrGroupId,RowCause,AccessLevel FROM ObjectApiName__Share

1
  • What i want to know is if an certan object is Private, Public or Public RO. If the Sharing table exists, like CustomObject__Share, then I know that this object is private ou public read only, if not it is public read/write. But with standard object I can't use this. For example if I change the object Account to Public Read/Write the object AccountShare keep existing.
    – Ivo Rocha
    Jan 17, 2013 at 22:46

You must log in to answer this question.

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