CRUD and FLS Enforcement for Reference Objects

Some SObjects, such as FeedItem and Task, contain a reference field that attaches it to a parent SObject of a different type. Apex code that creates, updates, or reads these reference fields must also check for read access on the parent SObject.

The example below creates a FeedItem and attaches it to an Account. The code must call isAccessible() on the referenced Account, in addition to the standard CRUD and FLS checks for FeedItem:

//ID of the referenced parent Account object
ID parentId = '001XXXXXXXXXX';
//FLS on the fields to create
List<String> fieldsToCheck = new List<String>{'Body', 'Title', 'ParentId'};
Map<String,Schema.SObjectField> allFields = Schema.SObjectType.FeedItem.fields.getMap();
for (String field : fieldsToCheck){
    if (!allFields.get(field).getDescribe().isCreateable()) {
        return '';
    }
}
//check for ParentId object access
if (!parentId.getSObjectType().getDescribe().isAccessible()){
    return '';
}
//actually create and insert the FeedItem
FeedItem fi = new FeedItem();
fi.Body = 'Hello';
fi.ParentId = parentId;
fi.Title = 'Post Title';
insert fi;
...