View source
<?php
namespace Drupal\field\Tests\EntityReference\Views;
use Drupal\simpletest\WebTestBase;
use Drupal\views\Views;
class SelectionTest extends WebTestBase {
public static $modules = [
'node',
'views',
'entity_reference_test',
'entity_test',
];
protected $nodes = array();
protected $field;
public function setUp() {
parent::setUp();
$type = $this
->drupalCreateContentType()
->id();
$node1 = $this
->drupalCreateNode(array(
'type' => $type,
));
$node2 = $this
->drupalCreateNode(array(
'type' => $type,
));
$node3 = $this
->drupalCreateNode();
foreach (array(
$node1,
$node2,
$node3,
) as $node) {
$this->nodes[$node
->getType()][$node
->id()] = $node
->label();
}
$field_storage = entity_create('field_storage_config', array(
'field_name' => 'test_field',
'entity_type' => 'entity_test',
'translatable' => FALSE,
'settings' => array(
'target_type' => 'node',
),
'type' => 'entity_reference',
'cardinality' => '1',
));
$field_storage
->save();
$field = entity_create('field_config', array(
'field_storage' => $field_storage,
'bundle' => 'test_bundle',
'settings' => array(
'handler' => 'views',
'handler_settings' => array(
'view' => array(
'view_name' => 'test_entity_reference',
'display_name' => 'entity_reference_1',
'arguments' => array(),
),
),
),
));
$field
->save();
$this->field = $field;
}
protected function assertResults(array $result) {
$success = FALSE;
foreach ($result as $node_type => $values) {
foreach ($values as $nid => $label) {
if (!($success = $this->nodes[$node_type][$nid] == trim(strip_tags($label)))) {
break;
}
}
}
$this
->assertTrue($success, 'Views selection handler returned expected values.');
}
public function testSelectionHandler() {
$handler = $this->container
->get('plugin.manager.entity_reference_selection')
->getSelectionHandler($this->field);
$result = $handler
->getReferenceableEntities();
$this
->assertResults($result);
}
public function testSelectionHandlerRelationship() {
$view = Views::getView('test_entity_reference');
$view
->setDisplay();
$view->displayHandlers
->get('default')
->setOption('relationships', array(
'test_relationship' => array(
'id' => 'uid',
'table' => 'node_field_data',
'field' => 'uid',
),
));
$view->displayHandlers
->get('default')
->setOption('filters', array(
'uid' => array(
'id' => 'uid',
'table' => 'users_field_data',
'field' => 'uid',
'relationship' => 'test_relationship',
),
));
$query_options = $view->display_handler
->getOption('query');
$query_options['options']['distinct'] = TRUE;
$view->display_handler
->setOption('query', $query_options);
$view
->save();
$handler = $this->container
->get('plugin.manager.entity_reference_selection')
->getSelectionHandler($this->field);
$result = $handler
->getReferenceableEntities();
$this
->assertResults($result);
}
}