3 namespace Drupal\views;
5 use Drupal\Core\Entity\ContentEntityType;
6 use Drupal\Core\Entity\EntityHandlerInterface;
7 use Drupal\Core\Entity\EntityManagerInterface;
8 use Drupal\Core\Entity\EntityTypeInterface;
9 use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
10 use Drupal\Core\Entity\Sql\TableMappingInterface;
11 use Drupal\Core\Extension\ModuleHandlerInterface;
12 use Drupal\Core\Field\FieldDefinitionInterface;
13 use Drupal\Core\StringTranslation\StringTranslationTrait;
14 use Drupal\Core\StringTranslation\TranslationInterface;
15 use Symfony\Component\DependencyInjection\Container;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
19 * Provides generic views integration for entities.
21 class EntityViewsData implements EntityHandlerInterface, EntityViewsDataInterface {
23 use StringTranslationTrait;
26 * Entity type for this views data handler instance.
28 * @var \Drupal\Core\Entity\EntityTypeInterface
30 protected $entityType;
33 * The storage used for this entity type.
35 * @var \Drupal\Core\Entity\Sql\SqlEntityStorageInterface
42 * @var \Drupal\Core\Extension\ModuleHandlerInterface
44 protected $moduleHandler;
47 * The translation manager.
49 * @var \Drupal\Core\StringTranslation\TranslationInterface
51 protected $translationManager;
54 * The field storage definitions for all base fields of the entity type.
56 * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
58 protected $fieldStorageDefinitions;
63 * @var \Drupal\Core\Entity\EntityManagerInterface
65 protected $entityManager;
68 * Constructs an EntityViewsData object.
70 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
71 * The entity type to provide views integration for.
72 * @param \Drupal\Core\Entity\Sql\SqlEntityStorageInterface $storage_controller
73 * The storage handler used for this entity type.
74 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
76 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
78 * @param \Drupal\Core\StringTranslation\TranslationInterface $translation_manager
79 * The translation manager.
81 public function __construct(EntityTypeInterface $entity_type, SqlEntityStorageInterface $storage_controller, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, TranslationInterface $translation_manager) {
82 $this->entityType = $entity_type;
83 $this->entityManager = $entity_manager;
84 $this->storage = $storage_controller;
85 $this->moduleHandler = $module_handler;
86 $this->setStringTranslation($translation_manager);
92 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
95 $container->get('entity.manager')->getStorage($entity_type->id()),
96 $container->get('entity.manager'),
97 $container->get('module_handler'),
98 $container->get('string_translation'),
99 $container->get('typed_data_manager')
104 * Gets the field storage definitions.
106 * @return \Drupal\Core\Field\FieldStorageDefinitionInterface[]
108 protected function getFieldStorageDefinitions() {
109 if (!isset($this->fieldStorageDefinitions)) {
110 $this->fieldStorageDefinitions = $this->entityManager->getFieldStorageDefinitions($this->entityType->id());
112 return $this->fieldStorageDefinitions;
118 public function getViewsData() {
121 $base_table = $this->entityType->getBaseTable() ?: $this->entityType->id();
122 $views_revision_base_table = NULL;
123 $revisionable = $this->entityType->isRevisionable();
124 $base_field = $this->entityType->getKey('id');
126 $revision_table = '';
128 $revision_table = $this->entityType->getRevisionTable() ?: $this->entityType->id() . '_revision';
131 $translatable = $this->entityType->isTranslatable();
134 $data_table = $this->entityType->getDataTable() ?: $this->entityType->id() . '_field_data';
137 // Some entity types do not have a revision data table defined, but still
138 // have a revision table name set in
139 // \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout() so we
140 // apply the same kind of logic.
141 $revision_data_table = '';
142 if ($revisionable && $translatable) {
143 $revision_data_table = $this->entityType->getRevisionDataTable() ?: $this->entityType->id() . '_field_revision';
145 $revision_field = $this->entityType->getKey('revision');
147 // Setup base information of the views data.
148 $data[$base_table]['table']['group'] = $this->entityType->getLabel();
149 $data[$base_table]['table']['provider'] = $this->entityType->getProvider();
151 $views_base_table = $base_table;
153 $views_base_table = $data_table;
155 $data[$views_base_table]['table']['base'] = [
156 'field' => $base_field,
157 'title' => $this->entityType->getLabel(),
158 'cache_contexts' => $this->entityType->getListCacheContexts(),
160 $data[$base_table]['table']['entity revision'] = FALSE;
162 if ($label_key = $this->entityType->getKey('label')) {
164 $data[$views_base_table]['table']['base']['defaults'] = [
165 'field' => $label_key,
166 'table' => $data_table,
170 $data[$views_base_table]['table']['base']['defaults'] = [
171 'field' => $label_key,
176 // Entity types must implement a list_builder in order to use Views'
177 // entity operations field.
178 if ($this->entityType->hasListBuilderClass()) {
179 $data[$base_table]['operations'] = [
181 'title' => $this->t('Operations links'),
182 'help' => $this->t('Provides links to perform entity operations.'),
183 'id' => 'entity_operations',
186 $data[$revision_table]['operations'] = [
188 'title' => $this->t('Operations links'),
189 'help' => $this->t('Provides links to perform entity operations.'),
190 'id' => 'entity_operations',
195 if ($this->entityType->hasViewBuilderClass()) {
196 $data[$base_table]['rendered_entity'] = [
198 'title' => $this->t('Rendered entity'),
199 'help' => $this->t('Renders an entity in a view mode.'),
200 'id' => 'rendered_entity',
205 // Setup relations to the revisions/property data.
207 $data[$base_table]['table']['join'][$data_table] = [
208 'left_field' => $base_field,
209 'field' => $base_field,
212 $data[$data_table]['table']['group'] = $this->entityType->getLabel();
213 $data[$data_table]['table']['provider'] = $this->entityType->getProvider();
214 $data[$data_table]['table']['entity revision'] = FALSE;
216 if ($revision_table) {
217 $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
218 $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
220 $views_revision_base_table = $revision_table;
221 if ($revision_data_table) {
222 $views_revision_base_table = $revision_data_table;
224 $data[$views_revision_base_table]['table']['entity revision'] = TRUE;
225 $data[$views_revision_base_table]['table']['base'] = [
226 'field' => $revision_field,
227 'title' => $this->t('@entity_type revisions', ['@entity_type' => $this->entityType->getLabel()]),
229 // Join the revision table to the base table.
230 $data[$views_revision_base_table]['table']['join'][$views_base_table] = [
231 'left_field' => $revision_field,
232 'field' => $revision_field,
236 if ($revision_data_table) {
237 $data[$revision_data_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
238 $data[$revision_data_table]['table']['entity revision'] = TRUE;
240 $data[$revision_table]['table']['join'][$revision_data_table] = [
241 'left_field' => $revision_field,
242 'field' => $revision_field,
247 // Add a filter for showing only the latest revisions of an entity.
248 $data[$revision_table]['latest_revision'] = [
249 'title' => $this->t('Is Latest Revision'),
250 'help' => $this->t('Restrict the view to only revisions that are the latest revision of their entity.'),
251 'filter' => ['id' => 'latest_revision'],
255 $this->addEntityLinks($data[$base_table]);
257 // Load all typed data definitions of all fields. This should cover each of
258 // the entity base, revision, data tables.
259 $field_definitions = $this->entityManager->getBaseFieldDefinitions($this->entityType->id());
260 /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
261 if ($table_mapping = $this->storage->getTableMapping($field_definitions)) {
262 // Fetch all fields that can appear in both the base table and the data
264 $entity_keys = $this->entityType->getKeys();
265 $duplicate_fields = array_intersect_key($entity_keys, array_flip(['id', 'revision', 'bundle']));
266 // Iterate over each table we have so far and collect field data for each.
267 // Based on whether the field is in the field_definitions provided by the
269 // @todo We should better just rely on information coming from the entity
271 // @todo https://www.drupal.org/node/2337511
272 foreach ($table_mapping->getTableNames() as $table) {
273 foreach ($table_mapping->getFieldNames($table) as $field_name) {
274 // To avoid confusing duplication in the user interface, for fields
275 // that are on both base and data tables, only add them on the data
276 // table (same for revision vs. revision data).
277 if ($data_table && ($table === $base_table || $table === $revision_table) && in_array($field_name, $duplicate_fields)) {
280 $this->mapFieldDefinition($table, $field_name, $field_definitions[$field_name], $table_mapping, $data[$table]);
284 foreach ($field_definitions as $field_definition) {
285 if ($table_mapping->requiresDedicatedTableStorage($field_definition->getFieldStorageDefinition())) {
286 $table = $table_mapping->getDedicatedDataTableName($field_definition->getFieldStorageDefinition());
288 $data[$table]['table']['group'] = $this->entityType->getLabel();
289 $data[$table]['table']['provider'] = $this->entityType->getProvider();
290 $data[$table]['table']['join'][$views_base_table] = [
291 'left_field' => $base_field,
292 'field' => 'entity_id',
294 ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
299 $revision_table = $table_mapping->getDedicatedRevisionTableName($field_definition->getFieldStorageDefinition());
301 $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
302 $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
303 $data[$revision_table]['table']['join'][$views_revision_base_table] = [
304 'left_field' => $revision_field,
305 'field' => 'entity_id',
307 ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
315 // Add the entity type key to each table generated.
316 $entity_type_id = $this->entityType->id();
317 array_walk($data, function (&$table_data) use ($entity_type_id) {
318 $table_data['table']['entity type'] = $entity_type_id;
325 * Sets the entity links in case corresponding link templates exist.
328 * The views data of the base table.
330 protected function addEntityLinks(array &$data) {
331 $entity_type_id = $this->entityType->id();
332 $t_arguments = ['@entity_type_label' => $this->entityType->getLabel()];
333 if ($this->entityType->hasLinkTemplate('canonical')) {
334 $data['view_' . $entity_type_id] = [
336 'title' => $this->t('Link to @entity_type_label', $t_arguments),
337 'help' => $this->t('Provide a view link to the @entity_type_label.', $t_arguments),
338 'id' => 'entity_link',
342 if ($this->entityType->hasLinkTemplate('edit-form')) {
343 $data['edit_' . $entity_type_id] = [
345 'title' => $this->t('Link to edit @entity_type_label', $t_arguments),
346 'help' => $this->t('Provide an edit link to the @entity_type_label.', $t_arguments),
347 'id' => 'entity_link_edit',
351 if ($this->entityType->hasLinkTemplate('delete-form')) {
352 $data['delete_' . $entity_type_id] = [
354 'title' => $this->t('Link to delete @entity_type_label', $t_arguments),
355 'help' => $this->t('Provide a delete link to the @entity_type_label.', $t_arguments),
356 'id' => 'entity_link_delete',
363 * Puts the views data for a single field onto the views data.
365 * @param string $table
366 * The table of the field to handle.
367 * @param string $field_name
368 * The name of the field to handle.
369 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
370 * The field definition defined in Entity::baseFieldDefinitions()
371 * @param \Drupal\Core\Entity\Sql\TableMappingInterface $table_mapping
372 * The table mapping information
373 * @param array $table_data
374 * A reference to a specific entity table (for example data_table) inside
377 protected function mapFieldDefinition($table, $field_name, FieldDefinitionInterface $field_definition, TableMappingInterface $table_mapping, &$table_data) {
378 // Create a dummy instance to retrieve property definitions.
379 $field_column_mapping = $table_mapping->getColumnNames($field_name);
380 $field_schema = $this->getFieldStorageDefinitions()[$field_name]->getSchema();
382 $field_definition_type = $field_definition->getType();
383 // Add all properties to views table data. We need an entry for each
384 // column of each field, with the first one given special treatment.
385 // @todo Introduce concept of the "main" column for a field, rather than
386 // assuming the first one is the main column. See also what the
387 // mapSingleFieldViewsData() method does with $first.
389 foreach ($field_column_mapping as $field_column_name => $schema_field_name) {
390 $table_data[$schema_field_name] = $this->mapSingleFieldViewsData($table, $field_name, $field_definition_type, $field_column_name, $field_schema['columns'][$field_column_name]['type'], $first, $field_definition);
391 $table_data[$schema_field_name]['entity field'] = $field_name;
397 * Provides the views data for a given data type and schema field.
399 * @param string $table
400 * The table of the field to handle.
401 * @param string $field_name
402 * The machine name of the field being processed.
403 * @param string $field_type
404 * The type of field being handled.
405 * @param string $column_name
406 * For fields containing multiple columns, the column name being processed.
407 * @param string $column_type
408 * Within the field, the column type being handled.
410 * TRUE if this is the first column within the field.
411 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
412 * The field definition.
415 * The modified views data field definition.
417 protected function mapSingleFieldViewsData($table, $field_name, $field_type, $column_name, $column_type, $first, FieldDefinitionInterface $field_definition) {
420 // Provide a nicer, less verbose label for the first column within a field.
421 // @todo Introduce concept of the "main" column for a field, rather than
422 // assuming the first one is the main column.
424 $views_field['title'] = $field_definition->getLabel();
427 $views_field['title'] = $field_definition->getLabel() . " ($column_name)";
430 if ($description = $field_definition->getDescription()) {
431 $views_field['help'] = $description;
434 // Set up the field, sort, argument, and filters, based on
435 // the column and/or field data type.
436 // @todo Allow field types to customize this.
437 // @see https://www.drupal.org/node/2337515
438 switch ($field_type) {
439 // Special case a few field types.
443 $views_field['field']['id'] = 'field';
444 $views_field['argument']['id'] = 'date';
445 $views_field['filter']['id'] = 'date';
446 $views_field['sort']['id'] = 'date';
450 $views_field['field']['id'] = 'field';
451 $views_field['argument']['id'] = 'language';
452 $views_field['filter']['id'] = 'language';
453 $views_field['sort']['id'] = 'standard';
457 $views_field['field']['id'] = 'field';
458 $views_field['argument']['id'] = 'numeric';
459 $views_field['filter']['id'] = 'boolean';
460 $views_field['sort']['id'] = 'standard';
464 // Let's render URIs as URIs by default, not links.
465 $views_field['field']['id'] = 'field';
466 $views_field['field']['default_formatter'] = 'string';
468 $views_field['argument']['id'] = 'string';
469 $views_field['filter']['id'] = 'string';
470 $views_field['sort']['id'] = 'standard';
474 case 'text_with_summary':
475 // Treat these three long text fields the same.
476 $field_type = 'text_long';
477 // Intentional fall-through here to the default processing!
480 // For most fields, the field type is generic enough to just use
481 // the column type to determine the filters etc.
482 switch ($column_type) {
492 $views_field['field']['id'] = 'field';
493 $views_field['argument']['id'] = 'numeric';
494 $views_field['filter']['id'] = 'numeric';
495 $views_field['sort']['id'] = 'standard';
501 case 'varchar_ascii':
506 $views_field['field']['id'] = 'field';
507 $views_field['argument']['id'] = 'string';
508 $views_field['filter']['id'] = 'string';
509 $views_field['sort']['id'] = 'standard';
513 $views_field['field']['id'] = 'field';
514 $views_field['argument']['id'] = 'standard';
515 $views_field['filter']['id'] = 'standard';
516 $views_field['sort']['id'] = 'standard';
520 // Do post-processing for a few field types.
522 $process_method = 'processViewsDataFor' . Container::camelize($field_type);
523 if (method_exists($this, $process_method)) {
524 $this->{$process_method}($table, $field_definition, $views_field, $column_name);
531 * Processes the views data for a language field.
533 * @param string $table
534 * The table the language field is added to.
535 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
536 * The field definition.
537 * @param array $views_field
538 * The views field data.
539 * @param string $field_column_name
540 * The field column being processed.
542 protected function processViewsDataForLanguage($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
543 // Apply special titles for the langcode field.
544 if ($field_definition->getName() == $this->entityType->getKey('langcode')) {
545 if ($table == $this->entityType->getDataTable() || $table == $this->entityType->getRevisionDataTable()) {
546 $views_field['title'] = $this->t('Translation language');
548 if ($table == $this->entityType->getBaseTable() || $table == $this->entityType->getRevisionTable()) {
549 $views_field['title'] = $this->t('Original language');
555 * Processes the views data for an entity reference field.
557 * @param string $table
558 * The table the language field is added to.
559 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
560 * The field definition.
561 * @param array $views_field
562 * The views field data.
563 * @param string $field_column_name
564 * The field column being processed.
566 protected function processViewsDataForEntityReference($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
568 // @todo Should the actual field handler respect that this just renders a
570 // @todo Create an optional entity field handler, that can render the
572 // @see https://www.drupal.org/node/2322949
574 if ($entity_type_id = $field_definition->getItemDefinition()->getSetting('target_type')) {
575 $entity_type = $this->entityManager->getDefinition($entity_type_id);
576 if ($entity_type instanceof ContentEntityType) {
577 $views_field['relationship'] = [
578 'base' => $this->getViewsTableForEntityType($entity_type),
579 'base field' => $entity_type->getKey('id'),
580 'label' => $entity_type->getLabel(),
581 'title' => $entity_type->getLabel(),
584 $views_field['field']['id'] = 'field';
585 $views_field['argument']['id'] = 'numeric';
586 $views_field['filter']['id'] = 'numeric';
587 $views_field['sort']['id'] = 'standard';
590 $views_field['field']['id'] = 'field';
591 $views_field['argument']['id'] = 'string';
592 $views_field['filter']['id'] = 'string';
593 $views_field['sort']['id'] = 'standard';
597 if ($field_definition->getName() == $this->entityType->getKey('bundle')) {
598 $views_field['filter']['id'] = 'bundle';
603 * Processes the views data for a text field with formatting.
605 * @param string $table
606 * The table the field is added to.
607 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
608 * The field definition.
609 * @param array $views_field
610 * The views field data.
611 * @param string $field_column_name
612 * The field column being processed.
614 protected function processViewsDataForTextLong($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
615 // Connect the text field to its formatter.
616 if ($field_column_name == 'value') {
617 $views_field['field']['format'] = $field_definition->getName() . '__format';
618 $views_field['field']['id'] = 'field';
623 * Processes the views data for a UUID field.
625 * @param string $table
626 * The table the field is added to.
627 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
628 * The field definition.
629 * @param array $views_field
630 * The views field data.
631 * @param string $field_column_name
632 * The field column being processed.
634 protected function processViewsDataForUuid($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
635 // It does not make sense for UUID fields to be click sortable.
636 $views_field['field']['click sortable'] = FALSE;
642 public function getViewsTableForEntityType(EntityTypeInterface $entity_type) {
643 return $entity_type->getDataTable() ?: $entity_type->getBaseTable();