file.views.inc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * @file
  4. * Provide views data for file.module.
  5. */
  6. use Drupal\field\FieldStorageConfigInterface;
  7. /**
  8. * Implements hook_field_views_data().
  9. *
  10. * Views integration for file fields. Adds a file relationship to the default
  11. * field data.
  12. *
  13. * @see views_field_default_views_data()
  14. */
  15. function file_field_views_data(FieldStorageConfigInterface $field_storage) {
  16. $data = views_field_default_views_data($field_storage);
  17. foreach ($data as $table_name => $table_data) {
  18. // Add the relationship only on the fid field.
  19. $data[$table_name][$field_storage->getName() . '_target_id']['relationship'] = [
  20. 'id' => 'standard',
  21. 'base' => 'file_managed',
  22. 'entity type' => 'file',
  23. 'base field' => 'fid',
  24. 'label' => t('file from @field_name', ['@field_name' => $field_storage->getName()]),
  25. ];
  26. }
  27. return $data;
  28. }
  29. /**
  30. * Implements hook_field_views_data_views_data_alter().
  31. *
  32. * Views integration to provide reverse relationships on file fields.
  33. */
  34. function file_field_views_data_views_data_alter(array &$data, FieldStorageConfigInterface $field_storage) {
  35. $entity_type_id = $field_storage->getTargetEntityTypeId();
  36. $entity_manager = \Drupal::entityTypeManager();
  37. $entity_type = $entity_manager->getDefinition($entity_type_id);
  38. $field_name = $field_storage->getName();
  39. $pseudo_field_name = 'reverse_' . $field_name . '_' . $entity_type_id;
  40. /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
  41. $table_mapping = $entity_manager->getStorage($entity_type_id)->getTableMapping();
  42. list($label) = views_entity_field_label($entity_type_id, $field_name);
  43. $data['file_managed'][$pseudo_field_name]['relationship'] = [
  44. 'title' => t('@entity using @field', ['@entity' => $entity_type->getLabel(), '@field' => $label]),
  45. 'label' => t('@field_name', ['@field_name' => $field_name]),
  46. 'group' => $entity_type->getLabel(),
  47. 'help' => t('Relate each @entity with a @field set to the file.', ['@entity' => $entity_type->getLabel(), '@field' => $label]),
  48. 'id' => 'entity_reverse',
  49. 'base' => $entity_type->getDataTable() ?: $entity_type->getBaseTable(),
  50. 'entity_type' => $entity_type_id,
  51. 'base field' => $entity_type->getKey('id'),
  52. 'field_name' => $field_name,
  53. 'field table' => $table_mapping->getDedicatedDataTableName($field_storage),
  54. 'field field' => $field_name . '_target_id',
  55. 'join_extra' => [
  56. 0 => [
  57. 'field' => 'deleted',
  58. 'value' => 0,
  59. 'numeric' => TRUE,
  60. ],
  61. ],
  62. ];
  63. }