3 namespace Drupal\KernelTests\Core\Entity\EntityReferenceSelection;
5 use Drupal\Component\Utility\Html;
6 use Drupal\field\Entity\FieldConfig;
7 use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
8 use Drupal\node\Entity\Node;
9 use Drupal\node\Entity\NodeType;
10 use Drupal\field\Entity\FieldStorageConfig;
13 * Tests sorting referenced items.
15 * @group entity_reference
17 class EntityReferenceSelectionSortTest extends EntityKernelTestBase {
24 public static $modules = ['node'];
26 protected function setUp() {
29 // Create an Article node type.
30 $article = NodeType::create([
35 // Test as a non-admin.
36 $normal_user = $this->createUser([], ['access content']);
37 \Drupal::currentUser()->setAccount($normal_user);
41 * Assert sorting by field and property.
43 public function testSort() {
44 // Add text field to entity, to sort by.
45 FieldStorageConfig::create([
46 'field_name' => 'field_text',
47 'entity_type' => 'node',
49 'entity_types' => ['node'],
53 'label' => 'Text Field',
54 'field_name' => 'field_text',
55 'entity_type' => 'node',
56 'bundle' => 'article',
61 // Build a set of test data.
66 'title' => 'Node published1 (<&>)',
77 'title' => 'Node published2 (<&>)',
89 foreach ($node_values as $key => $values) {
90 $node = Node::create($values);
93 $node_labels[$key] = Html::escape($node->label());
96 $selection_options = [
97 'target_type' => 'node',
98 'handler' => 'default',
99 'handler_settings' => [
100 'target_bundles' => NULL,
103 'field' => 'field_text.value',
104 'direction' => 'DESC',
108 $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
110 // Not only assert the result, but make sure the keys are sorted as
112 $result = $handler->getReferenceableEntities();
114 $nodes['published2']->id() => $node_labels['published2'],
115 $nodes['published1']->id() => $node_labels['published1'],
117 $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.');
119 // Assert sort by base field.
120 $selection_options['handler_settings']['sort'] = [
122 'direction' => 'ASC',
124 $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
125 $result = $handler->getReferenceableEntities();
127 $nodes['published1']->id() => $node_labels['published1'],
128 $nodes['published2']->id() => $node_labels['published2'],
130 $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');