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',
188 if ($this->entityType->hasViewBuilderClass()) {
189 $data[$base_table]['rendered_entity'] = [
191 'title' => $this->t('Rendered entity'),
192 'help' => $this->t('Renders an entity in a view mode.'),
193 'id' => 'rendered_entity',
198 // Setup relations to the revisions/property data.
200 $data[$base_table]['table']['join'][$data_table] = [
201 'left_field' => $base_field,
202 'field' => $base_field,
205 $data[$data_table]['table']['group'] = $this->entityType->getLabel();
206 $data[$data_table]['table']['provider'] = $this->entityType->getProvider();
207 $data[$data_table]['table']['entity revision'] = FALSE;
209 if ($revision_table) {
210 $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
211 $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
213 $views_revision_base_table = $revision_table;
214 if ($revision_data_table) {
215 $views_revision_base_table = $revision_data_table;
217 $data[$views_revision_base_table]['table']['entity revision'] = TRUE;
218 $data[$views_revision_base_table]['table']['base'] = [
219 'field' => $revision_field,
220 'title' => $this->t('@entity_type revisions', ['@entity_type' => $this->entityType->getLabel()]),
222 // Join the revision table to the base table.
223 $data[$views_revision_base_table]['table']['join'][$views_base_table] = [
224 'left_field' => $revision_field,
225 'field' => $revision_field,
229 if ($revision_data_table) {
230 $data[$revision_data_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
231 $data[$revision_data_table]['table']['entity revision'] = TRUE;
233 $data[$revision_table]['table']['join'][$revision_data_table] = [
234 'left_field' => $revision_field,
235 'field' => $revision_field,
241 $this->addEntityLinks($data[$base_table]);
243 // Load all typed data definitions of all fields. This should cover each of
244 // the entity base, revision, data tables.
245 $field_definitions = $this->entityManager->getBaseFieldDefinitions($this->entityType->id());
246 /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
247 if ($table_mapping = $this->storage->getTableMapping($field_definitions)) {
248 // Fetch all fields that can appear in both the base table and the data
250 $entity_keys = $this->entityType->getKeys();
251 $duplicate_fields = array_intersect_key($entity_keys, array_flip(['id', 'revision', 'bundle']));
252 // Iterate over each table we have so far and collect field data for each.
253 // Based on whether the field is in the field_definitions provided by the
255 // @todo We should better just rely on information coming from the entity
257 // @todo https://www.drupal.org/node/2337511
258 foreach ($table_mapping->getTableNames() as $table) {
259 foreach ($table_mapping->getFieldNames($table) as $field_name) {
260 // To avoid confusing duplication in the user interface, for fields
261 // that are on both base and data tables, only add them on the data
262 // table (same for revision vs. revision data).
263 if ($data_table && ($table === $base_table || $table === $revision_table) && in_array($field_name, $duplicate_fields)) {
266 $this->mapFieldDefinition($table, $field_name, $field_definitions[$field_name], $table_mapping, $data[$table]);
270 foreach ($field_definitions as $field_definition) {
271 if ($table_mapping->requiresDedicatedTableStorage($field_definition->getFieldStorageDefinition())) {
272 $table = $table_mapping->getDedicatedDataTableName($field_definition->getFieldStorageDefinition());
274 $data[$table]['table']['group'] = $this->entityType->getLabel();
275 $data[$table]['table']['provider'] = $this->entityType->getProvider();
276 $data[$table]['table']['join'][$views_base_table] = [
277 'left_field' => $base_field,
278 'field' => 'entity_id',
280 ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
285 $revision_table = $table_mapping->getDedicatedRevisionTableName($field_definition->getFieldStorageDefinition());
287 $data[$revision_table]['table']['group'] = $this->t('@entity_type revision', ['@entity_type' => $this->entityType->getLabel()]);
288 $data[$revision_table]['table']['provider'] = $this->entityType->getProvider();
289 $data[$revision_table]['table']['join'][$views_revision_base_table] = [
290 'left_field' => $revision_field,
291 'field' => 'entity_id',
293 ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
301 // Add the entity type key to each table generated.
302 $entity_type_id = $this->entityType->id();
303 array_walk($data, function(&$table_data) use ($entity_type_id){
304 $table_data['table']['entity type'] = $entity_type_id;
311 * Sets the entity links in case corresponding link templates exist.
314 * The views data of the base table.
316 protected function addEntityLinks(array &$data) {
317 $entity_type_id = $this->entityType->id();
318 $t_arguments = ['@entity_type_label' => $this->entityType->getLabel()];
319 if ($this->entityType->hasLinkTemplate('canonical')) {
320 $data['view_' . $entity_type_id] = [
322 'title' => $this->t('Link to @entity_type_label', $t_arguments),
323 'help' => $this->t('Provide a view link to the @entity_type_label.', $t_arguments),
324 'id' => 'entity_link',
328 if ($this->entityType->hasLinkTemplate('edit-form')) {
329 $data['edit_' . $entity_type_id] = [
331 'title' => $this->t('Link to edit @entity_type_label', $t_arguments),
332 'help' => $this->t('Provide an edit link to the @entity_type_label.', $t_arguments),
333 'id' => 'entity_link_edit',
337 if ($this->entityType->hasLinkTemplate('delete-form')) {
338 $data['delete_' . $entity_type_id] = [
340 'title' => $this->t('Link to delete @entity_type_label', $t_arguments),
341 'help' => $this->t('Provide a delete link to the @entity_type_label.', $t_arguments),
342 'id' => 'entity_link_delete',
349 * Puts the views data for a single field onto the views data.
351 * @param string $table
352 * The table of the field to handle.
353 * @param string $field_name
354 * The name of the field to handle.
355 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
356 * The field definition defined in Entity::baseFieldDefinitions()
357 * @param \Drupal\Core\Entity\Sql\TableMappingInterface $table_mapping
358 * The table mapping information
359 * @param array $table_data
360 * A reference to a specific entity table (for example data_table) inside
363 protected function mapFieldDefinition($table, $field_name, FieldDefinitionInterface $field_definition, TableMappingInterface $table_mapping, &$table_data) {
364 // Create a dummy instance to retrieve property definitions.
365 $field_column_mapping = $table_mapping->getColumnNames($field_name);
366 $field_schema = $this->getFieldStorageDefinitions()[$field_name]->getSchema();
368 $field_definition_type = $field_definition->getType();
369 // Add all properties to views table data. We need an entry for each
370 // column of each field, with the first one given special treatment.
371 // @todo Introduce concept of the "main" column for a field, rather than
372 // assuming the first one is the main column. See also what the
373 // mapSingleFieldViewsData() method does with $first.
374 $multiple = (count($field_column_mapping) > 1);
376 foreach ($field_column_mapping as $field_column_name => $schema_field_name) {
377 $views_field_name = ($multiple) ? $field_name . '__' . $field_column_name : $field_name;
378 $table_data[$views_field_name] = $this->mapSingleFieldViewsData($table, $field_name, $field_definition_type, $field_column_name, $field_schema['columns'][$field_column_name]['type'], $first, $field_definition);
380 $table_data[$views_field_name]['entity field'] = $field_name;
386 * Provides the views data for a given data type and schema field.
388 * @param string $table
389 * The table of the field to handle.
390 * @param string $field_name
391 * The machine name of the field being processed.
392 * @param string $field_type
393 * The type of field being handled.
394 * @param string $column_name
395 * For fields containing multiple columns, the column name being processed.
396 * @param string $column_type
397 * Within the field, the column type being handled.
399 * TRUE if this is the first column within the field.
400 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
401 * The field definition.
404 * The modified views data field definition.
406 protected function mapSingleFieldViewsData($table, $field_name, $field_type, $column_name, $column_type, $first, FieldDefinitionInterface $field_definition) {
409 // Provide a nicer, less verbose label for the first column within a field.
410 // @todo Introduce concept of the "main" column for a field, rather than
411 // assuming the first one is the main column.
413 $views_field['title'] = $field_definition->getLabel();
416 $views_field['title'] = $field_definition->getLabel() . " ($column_name)";
419 if ($description = $field_definition->getDescription()) {
420 $views_field['help'] = $description;
423 // Set up the field, sort, argument, and filters, based on
424 // the column and/or field data type.
425 // @todo Allow field types to customize this.
426 // @see https://www.drupal.org/node/2337515
427 switch ($field_type) {
428 // Special case a few field types.
432 $views_field['field']['id'] = 'field';
433 $views_field['argument']['id'] = 'date';
434 $views_field['filter']['id'] = 'date';
435 $views_field['sort']['id'] = 'date';
439 $views_field['field']['id'] = 'field';
440 $views_field['argument']['id'] = 'language';
441 $views_field['filter']['id'] = 'language';
442 $views_field['sort']['id'] = 'standard';
446 $views_field['field']['id'] = 'field';
447 $views_field['argument']['id'] = 'numeric';
448 $views_field['filter']['id'] = 'boolean';
449 $views_field['sort']['id'] = 'standard';
453 // Let's render URIs as URIs by default, not links.
454 $views_field['field']['id'] = 'field';
455 $views_field['field']['default_formatter'] = 'string';
457 $views_field['argument']['id'] = 'string';
458 $views_field['filter']['id'] = 'string';
459 $views_field['sort']['id'] = 'standard';
463 case 'text_with_summary':
464 // Treat these three long text fields the same.
465 $field_type = 'text_long';
466 // Intentional fall-through here to the default processing!
469 // For most fields, the field type is generic enough to just use
470 // the column type to determine the filters etc.
471 switch ($column_type) {
481 $views_field['field']['id'] = 'field';
482 $views_field['argument']['id'] = 'numeric';
483 $views_field['filter']['id'] = 'numeric';
484 $views_field['sort']['id'] = 'standard';
490 case 'varchar_ascii':
495 $views_field['field']['id'] = 'field';
496 $views_field['argument']['id'] = 'string';
497 $views_field['filter']['id'] = 'string';
498 $views_field['sort']['id'] = 'standard';
502 $views_field['field']['id'] = 'field';
503 $views_field['argument']['id'] = 'standard';
504 $views_field['filter']['id'] = 'standard';
505 $views_field['sort']['id'] = 'standard';
509 // Do post-processing for a few field types.
511 $process_method = 'processViewsDataFor' . Container::camelize($field_type);
512 if (method_exists($this, $process_method)) {
513 $this->{$process_method}($table, $field_definition, $views_field, $column_name);
520 * Processes the views data for a language field.
522 * @param string $table
523 * The table the language field is added to.
524 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
525 * The field definition.
526 * @param array $views_field
527 * The views field data.
528 * @param string $field_column_name
529 * The field column being processed.
531 protected function processViewsDataForLanguage($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
532 // Apply special titles for the langcode field.
533 if ($field_definition->getName() == $this->entityType->getKey('langcode')) {
534 if ($table == $this->entityType->getDataTable() || $table == $this->entityType->getRevisionDataTable()) {
535 $views_field['title'] = $this->t('Translation language');
537 if ($table == $this->entityType->getBaseTable() || $table == $this->entityType->getRevisionTable()) {
538 $views_field['title'] = $this->t('Original language');
544 * Processes the views data for an entity reference field.
546 * @param string $table
547 * The table the language field is added to.
548 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
549 * The field definition.
550 * @param array $views_field
551 * The views field data.
552 * @param string $field_column_name
553 * The field column being processed.
555 protected function processViewsDataForEntityReference($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
557 // @todo Should the actual field handler respect that this just renders a
559 // @todo Create an optional entity field handler, that can render the
561 // @see https://www.drupal.org/node/2322949
563 if ($entity_type_id = $field_definition->getItemDefinition()->getSetting('target_type')) {
564 $entity_type = $this->entityManager->getDefinition($entity_type_id);
565 if ($entity_type instanceof ContentEntityType) {
566 $views_field['relationship'] = [
567 'base' => $this->getViewsTableForEntityType($entity_type),
568 'base field' => $entity_type->getKey('id'),
569 'label' => $entity_type->getLabel(),
570 'title' => $entity_type->getLabel(),
573 $views_field['field']['id'] = 'field';
574 $views_field['argument']['id'] = 'numeric';
575 $views_field['filter']['id'] = 'numeric';
576 $views_field['sort']['id'] = 'standard';
579 $views_field['field']['id'] = 'field';
580 $views_field['argument']['id'] = 'string';
581 $views_field['filter']['id'] = 'string';
582 $views_field['sort']['id'] = 'standard';
586 if ($field_definition->getName() == $this->entityType->getKey('bundle')) {
587 $views_field['filter']['id'] = 'bundle';
592 * Processes the views data for a text field with formatting.
594 * @param string $table
595 * The table the field is added to.
596 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
597 * The field definition.
598 * @param array $views_field
599 * The views field data.
600 * @param string $field_column_name
601 * The field column being processed.
603 protected function processViewsDataForTextLong($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
604 // Connect the text field to its formatter.
605 if ($field_column_name == 'value') {
606 $views_field['field']['format'] = $field_definition->getName() . '__format';
607 $views_field['field']['id'] = 'field';
612 * Processes the views data for a UUID field.
614 * @param string $table
615 * The table the field is added to.
616 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
617 * The field definition.
618 * @param array $views_field
619 * The views field data.
620 * @param string $field_column_name
621 * The field column being processed.
623 protected function processViewsDataForUuid($table, FieldDefinitionInterface $field_definition, array &$views_field, $field_column_name) {
624 // It does not make sense for UUID fields to be click sortable.
625 $views_field['field']['click sortable'] = FALSE;
631 public function getViewsTableForEntityType(EntityTypeInterface $entity_type) {
632 return $entity_type->getDataTable() ?: $entity_type->getBaseTable();