Same name and namespace in other branches
  1. 8.9.x core/modules/system/tests/modules/entity_test/entity_test.module \entity_test_entity_field_access()
  2. 9 core/modules/system/tests/modules/entity_test/entity_test.module \entity_test_entity_field_access()

Implements hook_entity_field_access().

See also

\Drupal\system\Tests\Entity\FieldAccessTest::testFieldAccess()

File

core/modules/system/tests/modules/entity_test/entity_test.module, line 404
Test module for the entity API providing several entity types for testing.

Code

function entity_test_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  if ($field_definition
    ->getName() == 'field_test_text') {
    if ($items) {
      if ($items->value == 'no access value') {
        return AccessResult::forbidden()
          ->addCacheableDependency($items
          ->getEntity());
      }
      elseif ($items->value == 'custom cache tag value') {
        return AccessResult::allowed()
          ->addCacheableDependency($items
          ->getEntity())
          ->addCacheTags([
          'entity_test_access:field_test_text',
        ]);
      }
      elseif ($operation == 'edit' && $items->value == 'no edit access value') {
        return AccessResult::forbidden()
          ->addCacheableDependency($items
          ->getEntity());
      }
    }
  }
  if ($field = \Drupal::state()
    ->get('views_field_access_test-field')) {
    if ($field_definition
      ->getName() === $field) {
      $result = AccessResult::allowedIfHasPermission($account, 'view test entity field');

      // For test purposes we want to actively deny access.
      if ($result
        ->isNeutral()) {
        $result = AccessResult::forbidden();
      }
      return $result;
    }
  }

  // No opinion.
  return AccessResult::neutral();
}