I have some code that checks user access to a certain field using hook_field_access below.
The code runs fine when viewing nodes normally, but throws an error when viewing a node of type 'lesson' through a View:
Notice: Trying to get property of non-object
The error comes from the check for entity type: $entity->type == 'lesson'
If I debug with:
dpm($entity->type);
I get the right value ('lesson'), so the check seems to work.
How can I resolve this error?
function HOOK_utility_field_access($op, $field, $entity_type, $entity, $account) {
//Check video field only when attached to 'lesson'.
if ($field['field_name'] == 'field_video' && $entity_type == 'node' && $op == 'view' && $entity->type == 'lesson') {
//Grant access only if user is logged in.
if ($account->uid > 0) {
return TRUE;
}
return FALSE;
}
}
$entity
is populated and once it isn't?is_object()
might be better but yeah, that would do it. Sometimes these hooks get called for new entities, and$entity
isn't available yet. Or there may be a dodgy field in your install somewhere which is lacking an entity when it should have one in this context. If you're not up for a serious debug sesh then yeah, bandage it up :)