function FieldAccessTest::testFieldAccess

Same name in this branch
  1. 11.x core/modules/field/tests/src/Functional/FieldAccessTest.php \Drupal\Tests\field\Functional\FieldAccessTest::testFieldAccess()
Same name in other branches
  1. 9 core/modules/field/tests/src/Functional/FieldAccessTest.php \Drupal\Tests\field\Functional\FieldAccessTest::testFieldAccess()
  2. 9 core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php \Drupal\KernelTests\Core\Field\FieldAccessTest::testFieldAccess()
  3. 8.9.x core/modules/field/tests/src/Functional/FieldAccessTest.php \Drupal\Tests\field\Functional\FieldAccessTest::testFieldAccess()
  4. 8.9.x core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php \Drupal\KernelTests\Core\Field\FieldAccessTest::testFieldAccess()
  5. 10 core/modules/field/tests/src/Functional/FieldAccessTest.php \Drupal\Tests\field\Functional\FieldAccessTest::testFieldAccess()
  6. 10 core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php \Drupal\KernelTests\Core\Field\FieldAccessTest::testFieldAccess()

Tests hook_entity_field_access() and hook_entity_field_access_alter().

See also

entity_test_entity_field_access()

entity_test_entity_field_access_alter()

File

core/tests/Drupal/KernelTests/Core/Field/FieldAccessTest.php, line 72

Class

FieldAccessTest
Tests Field level access hooks.

Namespace

Drupal\KernelTests\Core\Field

Code

public function testFieldAccess() : void {
    $values = [
        'name' => $this->randomMachineName(),
        'user_id' => 1,
        'field_test_text' => [
            'value' => 'no access value',
            'format' => 'full_html',
        ],
    ];
    $entity = EntityTest::create($values);
    // Create a dummy user account for testing access with.
    $values = [
        'name' => 'test',
    ];
    $account = User::create($values);
    $this->assertFalse($entity->field_test_text
        ->access('view', $account), 'Access to the field was denied.');
    $expected = AccessResult::forbidden()->addCacheableDependency($entity);
    $this->assertEquals($expected, $entity->field_test_text
        ->access('view', $account, TRUE), 'Access to the field was denied.');
    $entity->field_test_text = 'access alter value';
    $this->assertFalse($entity->field_test_text
        ->access('view', $account), 'Access to the field was denied.');
    $this->assertEquals($expected, $entity->field_test_text
        ->access('view', $account, TRUE), 'Access to the field was denied.');
    $entity->field_test_text = 'standard value';
    $this->assertTrue($entity->field_test_text
        ->access('view', $account), 'Access to the field was granted.');
    $this->assertEquals(AccessResult::allowed(), $entity->field_test_text
        ->access('view', $account, TRUE), 'Access to the field was granted.');
}

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