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
Terry PostTerry Post 

Apex compile error when accessing Parent relationship on ObjectPermissions object

I came across an issue when attempting to access certain fields on the PermissionSet object when traversing the Parent relationship from the ObjectPermissions object. The Apex compiler fails and says variable does not exist when I try to reference the Parent.IsOwnedByProfile and Parent.Label fields. It works fine to reference Parent.Name and even Parent.Profile.Name, but fails when attempting to access other fields.

Here's some sample code:
List<ObjectPermissions> opList = [SELECT Id, SObjectType, ParentId, Parent.IsOwnedByProfile, Parent.Label, Parent.Name, Parent.Profile.Name FROM ObjectPermissions LIMIT 10];

if(!opList.isEmpty()) {
    system.debug('Parent Name: ' + opList[0].Parent.Name);  //This works just fine
    system.debug('Label: ' + opList[0].Parent.Label);       //This causes a compile error (Variable does not exist: Label)

    PermissionSet newPS = new PermissionSet();
    newPS = opList[0].Parent;
    system.debug('Label: ' + newPS.Label); //This works fine
}
Attempting to access the Label field with dot notation via the Parent relationship fails, but once I create a new instance of a PermissionSet and assign it to the same parent, then I can access it just fine.

This kind of feels like this is a polymorphic relationship. Epsecially given the generic "Parent" name of the relationship. The API documentation for the ObjectPermissions object does not mention any polymorphism for the ParentId field however. 

In any case, I was able to work around this by running a separate query for the parent PermissionSet records and creating a map to do lookups, but I found this behavior odd.

Does anyone know why this is happening and/or can confirm relationship polymorphism?

Thanks!
Deepali KulshresthaDeepali Kulshrestha
Hi Terry ,

Try this

string qry = 'SELECT Parent.Profile.Name, Parent.Profile.ID, ParentID, Parent.Label FROM ObjectPermissions WHERE (ParentId IN (SELECT PermissionSetId FROM PermissionSetAssignment))';
    List<ObjectPermissions> opList= New List<ObjectPermissions>();
    opList= Database.query(qry);
if(!opList.isEmpty()) {

    system.debug('Parent Name: ' + opList[0].Parent.Name);  

    system.debug('Label: ' + opList[0].Parent.Label);       

    PermissionSet newPS = new PermissionSet();

    newPS = opList[0].Parent;

    system.debug('Label: ' + newPS.Label); 
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
Terry PostTerry Post
Hi Deepali,

Thanks for responding, but unfortunately no, this did not resolve the issue. Line 8 in your code still causes a compile time error due to the Label field not being recognized. 

Thanks!