3

I am building a package where I use child-to-parent query to get the data, and I allow users to select fields and relationships they want. This may lead to problems like this, or in my case when I try to select [SELECT CreatedBy.AboutMe FROM AccountFeed].

I want to prevent this from happening and forbid users to select polymorphic relationships.

My current approach to detect such relationship is following

static Boolean isPolymorphic(DescribeFieldResult fd) {
    return fd.getReferenceTo().size() > 1
}

which fails to detect fields like AccountFeed.CreatedById, AccountFeed.RelatedRecordId, AccountFeed.InsertedById or SocialPost.ParentId as polymorphic and which leads to errors like No such column as 'AboutMe' on Entity Name.

Another way would be just to run the query and check if it fails like following

static Boolean isPolymorphic(DescribeFieldResult fd) {
    try {
        List<SObject> records = Database.query('SELECT ' + fd.getRelationshipName() + '.AboutMe FROM AccountFeed');
        return false;
    } catch (System.QueryException e) {
        return true;
    }
}

however, this way looks too ugly.

Is there an effective way to detect polymorphic fields to prevent users to select them?

2 Answers 2

3

Use the isNamePointing method to determine if a field is polymorphic (when true, it is polymorphic). Your function can be written simply as:

static Boolean isPolymorphic(DescribeFieldResult fd) {
  return fd.isNamePointing();
}

... Though at this point, you don't really need a function for this. You also don't need to burn a query.

1
  • interesting....
    – Patlatus
    Sep 22, 2021 at 19:29
0

FieldDefinition object has property IsPolymorphicForeignKey which can be queried to determine whether the foreign key includes multiple object types (true) or not (false), so the function isPolymorphic can be implemented in the following way

static Boolean isPolymorphic(DescribeFieldResult fd) {
    FieldDefinition def = [SELECT IsPolymorphicForeignKey FROM FieldDefinition WHERE EntityDefinitionId = 'AccountFeed' AND QualifiedAPIName = :fd.getName()];
    return def.IsPolymorphicForeignKey;
}

You must log in to answer this question.

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