Check object accessibility for dynamic object types!

Have you wanted to check object accessibility for dynamic objects?  Try  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.

try {
MyObject = [Select Id FROM :ObjectType WHERE Id = :ObjectId];
} catch {
MyObject = new Lead(); // set it to anything blank.
message = 'No Permission';

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.

Asked on April 5, 2019 in APEX.
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.