function UserEntityReferenceTest::testUserSelectionByRole

Same name in other branches
  1. 9 core/modules/user/tests/src/Kernel/UserEntityReferenceTest.php \Drupal\Tests\user\Kernel\UserEntityReferenceTest::testUserSelectionByRole()
  2. 8.9.x core/modules/user/tests/src/Kernel/UserEntityReferenceTest.php \Drupal\Tests\user\Kernel\UserEntityReferenceTest::testUserSelectionByRole()
  3. 11.x core/modules/user/tests/src/Kernel/UserEntityReferenceTest.php \Drupal\Tests\user\Kernel\UserEntityReferenceTest::testUserSelectionByRole()

Tests user selection by roles.

File

core/modules/user/tests/src/Kernel/UserEntityReferenceTest.php, line 59

Class

UserEntityReferenceTest
Tests the user reference field functionality.

Namespace

Drupal\Tests\user\Kernel

Code

public function testUserSelectionByRole() : void {
    $field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
    $handler_settings = $field_definition->getSetting('handler_settings');
    $handler_settings['filter']['role'] = [
        $this->role1
            ->id() => $this->role1
            ->id(),
        $this->role2
            ->id() => 0,
    ];
    $handler_settings['filter']['type'] = 'role';
    $field_definition->setSetting('handler_settings', $handler_settings);
    $field_definition->save();
    // cspell:ignore aabb aabbb aabbbb aabbbb
    $user1 = $this->createUser([], 'aabb');
    $user1->addRole($this->role1
        ->id())
        ->save();
    $user2 = $this->createUser([], 'aabbb');
    $user2->addRole($this->role1
        ->id())
        ->save();
    $user3 = $this->createUser([], 'aabbbb');
    $user3->addRole($this->role2
        ->id())
        ->save();
    
    /** @var \Drupal\Core\Entity\EntityAutocompleteMatcherInterface $autocomplete */
    $autocomplete = \Drupal::service('entity.autocomplete_matcher');
    $matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabb');
    $this->assertCount(2, $matches);
    $users = [];
    foreach ($matches as $match) {
        $users[] = $match['label'];
    }
    $this->assertContains($user1->label(), $users);
    $this->assertContains($user2->label(), $users);
    $this->assertNotContains($user3->label(), $users);
    $matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabbbb');
    $this->assertCount(0, $matches);
}

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