How to check for entity type in Views when using hook_field_access? 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-&gt;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' &amp;&amp; $entity_type == 'node' &amp;&amp; $op == 'view' &amp;&amp; $entity-&gt;type == 'lesson') {

    //Grant access only if user is logged in.
    if ($account-&gt;uid &gt; 0) {
      return TRUE;
    }
    return FALSE;
  }
}
Based on @clive's comment above, I adjusted the code to check that $entity is actually present. I'm not sure if this is a problem unique to my install or not. I only saw the error when viewing a node of type 'lesson' through a paged view that depends on some custom relationship code, so entirely possible the error is mine somewhere in a custom module.

function HOOK_field_access($op, $field, $entity_type, $entity, $account) {

      //Check to make sure we have an entity. Abort if not.
      if (is_object($entity)) {

        //Check video field only when attached to 'lesson'.
        if ($field['field_name'] == 'field_video' &amp;&amp; $entity_type == 'node' &amp;&amp; $op == 'view' &amp;&amp; $entity-&gt;type == 'lesson') {

          //Grant access only if user is logged in.
          if ($account-&gt;uid &gt; 0) {
            return TRUE;
          }
          return FALSE;
        }
      }
    }