function entity_test_entity_field_access

Same name and namespace in other branches
  1. 9 core/modules/system/tests/modules/entity_test/entity_test.module \entity_test_entity_field_access()
  2. 8.9.x core/modules/system/tests/modules/entity_test/entity_test.module \entity_test_entity_field_access()
  3. 10 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

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();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.