function EntityTestHooks::entityFieldAccess

Implements hook_entity_field_access().

See also

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

File

core/modules/system/tests/modules/entity_test/src/Hook/EntityTestHooks.php, line 290

Class

EntityTestHooks
Hook implementations for entity_test.

Namespace

Drupal\entity_test\Hook

Code

public function entityFieldAccess($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.