+ Start a Discussion

Check object accessibility for dynamic object types?

How can I check if a user can access a particular object?


I see this code snippet


<apex:pageBlock rendered="{!$ObjectType.Lead.accessible}">


But how can I check for a specific sObject myObject?   I want to display an error message if the user does not have access to view the object in myObject.





It should just be a matter of replacing Lead with the API name for your object.  E.g. if the object is MyObject, then the code would be:


<apex:pageBlock rendered="{!$ObjectType.MyObject__c.accessible}">


Of course, if what you are actually asking is how to check if the user has permission to access a particular record (i.e. instance of an object) its a little more involved.  One way is:



Use a method from a class declared as with sharing, and try to retrieve the object via SOQL based on its id.  As with sharing respects the sharing rules, if the user doesn't have acccess then the SOQL query will retrieve no values.


If your controller isn't declared as with sharing, you'll need to provide a utility class that does and execute a method from that.




try {

  MyObject = [Select Id FROM :ObjectType WHERE Id = :ObjectId];

} catch {

  MyObject = new Lead(); // set it to anything blank.

  message = 'No Permission';



Something like that.  I bet the catch even returns the specific error type.


Be careful to ensure you only execute this from a class defined as "with sharing".  


VisualForce controllers run as the system user and thus have access to everything regardless of the actual logged in user viewing the page.