views.views.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. <?php
  2. /**
  3. * @file
  4. * Provide views data that isn't tied to any other module.
  5. */
  6. use Drupal\Component\Utility\NestedArray;
  7. use Drupal\Core\Entity\EntityStorageInterface;
  8. use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
  9. use Drupal\Core\Render\Markup;
  10. use Drupal\field\Entity\FieldConfig;
  11. use Drupal\field\FieldConfigInterface;
  12. use Drupal\field\FieldStorageConfigInterface;
  13. use Drupal\system\ActionConfigEntityInterface;
  14. /**
  15. * Implements hook_views_data().
  16. */
  17. function views_views_data() {
  18. $data['views']['table']['group'] = t('Global');
  19. $data['views']['table']['join'] = [
  20. // #global is a special flag which allows a table to appear all the time.
  21. '#global' => [],
  22. ];
  23. $data['views']['random'] = [
  24. 'title' => t('Random'),
  25. 'help' => t('Randomize the display order.'),
  26. 'sort' => [
  27. 'id' => 'random',
  28. ],
  29. ];
  30. $data['views']['null'] = [
  31. 'title' => t('Null'),
  32. 'help' => t('Allow a contextual filter value to be ignored. The query will not be altered by this contextual filter value. Can be used when contextual filter values come from the URL, and a part of the URL needs to be ignored.'),
  33. 'argument' => [
  34. 'id' => 'null',
  35. ],
  36. ];
  37. $data['views']['nothing'] = [
  38. 'title' => t('Custom text'),
  39. 'help' => t('Provide custom text or link.'),
  40. 'field' => [
  41. 'id' => 'custom',
  42. ],
  43. ];
  44. $data['views']['counter'] = [
  45. 'title' => t('View result counter'),
  46. 'help' => t('Displays the actual position of the view result'),
  47. 'field' => [
  48. 'id' => 'counter',
  49. ],
  50. ];
  51. $data['views']['area'] = [
  52. 'title' => t('Text area'),
  53. 'help' => t('Provide markup text for the area.'),
  54. 'area' => [
  55. 'id' => 'text',
  56. ],
  57. ];
  58. $data['views']['area_text_custom'] = [
  59. 'title' => t('Unfiltered text'),
  60. 'help' => t('Add unrestricted, custom text or markup. This is similar to the custom text field.'),
  61. 'area' => [
  62. 'id' => 'text_custom',
  63. ],
  64. ];
  65. $data['views']['title'] = [
  66. 'title' => t('Title override'),
  67. 'help' => t('Override the default view title for this view. This is useful to display an alternative title when a view is empty.'),
  68. 'area' => [
  69. 'id' => 'title',
  70. 'sub_type' => 'empty',
  71. ],
  72. ];
  73. $data['views']['view'] = [
  74. 'title' => t('View area'),
  75. 'help' => t('Insert a view inside an area.'),
  76. 'area' => [
  77. 'id' => 'view',
  78. ],
  79. ];
  80. $data['views']['result'] = [
  81. 'title' => t('Result summary'),
  82. 'help' => t('Shows result summary, for example the items per page.'),
  83. 'area' => [
  84. 'id' => 'result',
  85. ],
  86. ];
  87. $data['views']['messages'] = [
  88. 'title' => t('Messages'),
  89. 'help' => t('Displays messages in an area.'),
  90. 'area' => [
  91. 'id' => 'messages',
  92. ],
  93. ];
  94. $data['views']['http_status_code'] = [
  95. 'title' => t('Response status code'),
  96. 'help' => t('Alter the HTTP response status code used by this view, mostly helpful for empty results.'),
  97. 'area' => [
  98. 'id' => 'http_status_code',
  99. ],
  100. ];
  101. $data['views']['combine'] = [
  102. 'title' => t('Combine fields filter'),
  103. 'help' => t('Combine multiple fields together and search by them.'),
  104. 'filter' => [
  105. 'id' => 'combine',
  106. ],
  107. ];
  108. $data['views']['dropbutton'] = [
  109. 'title' => t('Dropbutton'),
  110. 'help' => t('Display fields in a dropbutton.'),
  111. 'field' => [
  112. 'id' => 'dropbutton',
  113. ],
  114. ];
  115. $data['views']['display_link'] = [
  116. 'title' => t('Link to display'),
  117. 'help' => t('Displays a link to a path-based display of this view while keeping the filter criteria, sort criteria, pager settings and contextual filters.'),
  118. 'area' => [
  119. 'id' => 'display_link',
  120. ],
  121. ];
  122. // Registers an entity area handler per entity type.
  123. foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type_id => $entity_type) {
  124. // Excludes entity types, which cannot be rendered.
  125. if ($entity_type->hasViewBuilderClass()) {
  126. $label = $entity_type->getLabel();
  127. $data['views']['entity_' . $entity_type_id] = [
  128. 'title' => t('Rendered entity - @label', ['@label' => $label]),
  129. 'help' => t('Displays a rendered @label entity in an area.', ['@label' => $label]),
  130. 'area' => [
  131. 'entity_type' => $entity_type_id,
  132. 'id' => 'entity',
  133. ],
  134. ];
  135. }
  136. }
  137. // Registers an action bulk form per entity.
  138. foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type => $entity_info) {
  139. $actions = array_filter(\Drupal::entityTypeManager()->getStorage('action')->loadMultiple(), function (ActionConfigEntityInterface $action) use ($entity_type) {
  140. return $action->getType() == $entity_type;
  141. });
  142. if (empty($actions)) {
  143. continue;
  144. }
  145. $data[$entity_info->getBaseTable()][$entity_type . '_bulk_form'] = [
  146. 'title' => t('Bulk update'),
  147. 'help' => t('Allows users to apply an action to one or more items.'),
  148. 'field' => [
  149. 'id' => 'bulk_form',
  150. ],
  151. ];
  152. }
  153. // Registers views data for the entity itself.
  154. foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type_id => $entity_type) {
  155. if ($entity_type->hasHandlerClass('views_data')) {
  156. /** @var \Drupal\views\EntityViewsDataInterface $views_data */
  157. $views_data = \Drupal::entityTypeManager()->getHandler($entity_type_id, 'views_data');
  158. $data = NestedArray::mergeDeep($data, $views_data->getViewsData());
  159. }
  160. }
  161. // Field modules can implement hook_field_views_data() to override the default
  162. // behavior for adding fields.
  163. $module_handler = \Drupal::moduleHandler();
  164. $entity_type_manager = \Drupal::entityTypeManager();
  165. if ($entity_type_manager->hasDefinition('field_storage_config')) {
  166. /** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
  167. foreach ($entity_type_manager->getStorage('field_storage_config')->loadMultiple() as $field_storage) {
  168. if (_views_field_get_entity_type_storage($field_storage)) {
  169. $result = (array) $module_handler->invoke($field_storage->getTypeProvider(), 'field_views_data', [$field_storage]);
  170. if (empty($result)) {
  171. $result = views_field_default_views_data($field_storage);
  172. }
  173. $module_handler->alter('field_views_data', $result, $field_storage);
  174. if (is_array($result)) {
  175. $data = NestedArray::mergeDeep($result, $data);
  176. }
  177. }
  178. }
  179. }
  180. return $data;
  181. }
  182. /**
  183. * Implements hook_views_data_alter().
  184. *
  185. * Field modules can implement hook_field_views_data_views_data_alter() to
  186. * alter the views data on a per field basis. This is weirdly named so as
  187. * not to conflict with the \Drupal::moduleHandler()->alter('field_views_data')
  188. * in views_views_data().
  189. */
  190. function views_views_data_alter(&$data) {
  191. $entity_manager = \Drupal::entityTypeManager();
  192. if (!$entity_manager->hasDefinition('field_storage_config')) {
  193. return;
  194. }
  195. /** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
  196. foreach ($entity_manager->getStorage('field_storage_config')->loadMultiple() as $field_storage) {
  197. if (_views_field_get_entity_type_storage($field_storage)) {
  198. $function = $field_storage->getTypeProvider() . '_field_views_data_views_data_alter';
  199. if (function_exists($function)) {
  200. $function($data, $field_storage);
  201. }
  202. }
  203. }
  204. }
  205. /**
  206. * Determines whether the entity type the field appears in is SQL based.
  207. *
  208. * @param \Drupal\field\FieldStorageConfigInterface $field_storage
  209. * The field storage definition.
  210. *
  211. * @return \Drupal\Core\Entity\Sql\SqlContentEntityStorage
  212. * Returns the entity type storage if supported.
  213. */
  214. function _views_field_get_entity_type_storage(FieldStorageConfigInterface $field_storage) {
  215. $result = FALSE;
  216. $entity_manager = \Drupal::entityTypeManager();
  217. if ($entity_manager->hasDefinition($field_storage->getTargetEntityTypeId())) {
  218. $storage = $entity_manager->getStorage($field_storage->getTargetEntityTypeId());
  219. $result = $storage instanceof SqlContentEntityStorage ? $storage : FALSE;
  220. }
  221. return $result;
  222. }
  223. /**
  224. * Returns the label of a certain field.
  225. *
  226. * Therefore it looks up in all bundles to find the most used field.
  227. */
  228. function views_entity_field_label($entity_type, $field_name) {
  229. $label_counter = [];
  230. $all_labels = [];
  231. // Count the amount of fields per label per field storage.
  232. $entity_field_manager = \Drupal::service('entity_field.manager');
  233. foreach (array_keys(\Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type)) as $bundle) {
  234. $bundle_fields = array_filter($entity_field_manager->getFieldDefinitions($entity_type, $bundle), function ($field_definition) {
  235. return $field_definition instanceof FieldConfigInterface;
  236. });
  237. if (isset($bundle_fields[$field_name])) {
  238. $field = $bundle_fields[$field_name];
  239. $label = $field->getLabel();
  240. $label_counter[$label] = isset($label_counter[$label]) ? ++$label_counter[$label] : 1;
  241. $all_labels[$label] = TRUE;
  242. }
  243. }
  244. if (empty($label_counter)) {
  245. return [$field_name, $all_labels];
  246. }
  247. // Sort the field labels by it most used label and return the most used one.
  248. // If the counts are equal, sort by the label to ensure the result is
  249. // deterministic.
  250. uksort($label_counter, function ($a, $b) use ($label_counter) {
  251. if ($label_counter[$a] === $label_counter[$b]) {
  252. return strcmp($a, $b);
  253. }
  254. return $label_counter[$a] > $label_counter[$b] ? -1 : 1;
  255. });
  256. $label_counter = array_keys($label_counter);
  257. return [$label_counter[0], $all_labels];
  258. }
  259. /**
  260. * Default views data implementation for a field.
  261. *
  262. * @param \Drupal\field\FieldStorageConfigInterface $field_storage
  263. * The field definition.
  264. *
  265. * @return array
  266. * The default views data for the field.
  267. */
  268. function views_field_default_views_data(FieldStorageConfigInterface $field_storage) {
  269. $data = [];
  270. // Check the field type is available.
  271. if (!\Drupal::service('plugin.manager.field.field_type')->hasDefinition($field_storage->getType())) {
  272. return $data;
  273. }
  274. // Check the field storage has fields.
  275. if (!$field_storage->getBundles()) {
  276. return $data;
  277. }
  278. // Ignore custom storage too.
  279. if ($field_storage->hasCustomStorage()) {
  280. return $data;
  281. }
  282. // Check whether the entity type storage is supported.
  283. $storage = _views_field_get_entity_type_storage($field_storage);
  284. if (!$storage) {
  285. return $data;
  286. }
  287. $field_name = $field_storage->getName();
  288. $field_columns = $field_storage->getColumns();
  289. // Grab information about the entity type tables.
  290. // We need to join to both the base table and the data table, if available.
  291. $entity_type_manager = \Drupal::entityTypeManager();
  292. $entity_type_id = $field_storage->getTargetEntityTypeId();
  293. $entity_type = $entity_type_manager->getDefinition($entity_type_id);
  294. if (!$base_table = $entity_type->getBaseTable()) {
  295. // We cannot do anything if for some reason there is no base table.
  296. return $data;
  297. }
  298. $entity_tables = [$base_table => $entity_type_id];
  299. // Some entities may not have a data table.
  300. $data_table = $entity_type->getDataTable();
  301. if ($data_table) {
  302. $entity_tables[$data_table] = $entity_type_id;
  303. }
  304. $entity_revision_table = $entity_type->getRevisionTable();
  305. $supports_revisions = $entity_type->hasKey('revision') && $entity_revision_table;
  306. if ($supports_revisions) {
  307. $entity_tables[$entity_revision_table] = $entity_type_id;
  308. $entity_revision_data_table = $entity_type->getRevisionDataTable();
  309. if ($entity_revision_data_table) {
  310. $entity_tables[$entity_revision_data_table] = $entity_type_id;
  311. }
  312. }
  313. // Description of the field tables.
  314. // @todo Generalize this code to make it work with any table layout. See
  315. // https://www.drupal.org/node/2079019.
  316. $table_mapping = $storage->getTableMapping();
  317. $field_tables = [
  318. EntityStorageInterface::FIELD_LOAD_CURRENT => [
  319. 'table' => $table_mapping->getDedicatedDataTableName($field_storage),
  320. 'alias' => "{$entity_type_id}__{$field_name}",
  321. ],
  322. ];
  323. if ($supports_revisions) {
  324. $field_tables[EntityStorageInterface::FIELD_LOAD_REVISION] = [
  325. 'table' => $table_mapping->getDedicatedRevisionTableName($field_storage),
  326. 'alias' => "{$entity_type_id}_revision__{$field_name}",
  327. ];
  328. }
  329. // Determine if the fields are translatable.
  330. $bundles_names = $field_storage->getBundles();
  331. $translation_join_type = FALSE;
  332. $fields = [];
  333. $translatable_configs = [];
  334. $untranslatable_configs = [];
  335. $untranslatable_config_bundles = [];
  336. foreach ($bundles_names as $bundle) {
  337. $fields[$bundle] = FieldConfig::loadByName($entity_type->id(), $bundle, $field_name);
  338. }
  339. foreach ($fields as $bundle => $config_entity) {
  340. if (!empty($config_entity)) {
  341. if ($config_entity->isTranslatable()) {
  342. $translatable_configs[$bundle] = $config_entity;
  343. }
  344. else {
  345. $untranslatable_configs[$bundle] = $config_entity;
  346. }
  347. }
  348. else {
  349. // https://www.drupal.org/node/2451657#comment-11462881
  350. \Drupal::logger('views')->error(
  351. 'A non-existent config entity name returned by FieldStorageConfigInterface::getBundles(): entity type: %entity_type, bundle: %bundle, field name: %field',
  352. [
  353. '%entity_type' => $entity_type->id(),
  354. '%bundle' => $bundle,
  355. '%field' => $field_name,
  356. ]
  357. );
  358. }
  359. }
  360. // If the field is translatable on all the bundles, there will be a join on
  361. // the langcode.
  362. if (!empty($translatable_configs) && empty($untranslatable_configs)) {
  363. $translation_join_type = 'language';
  364. }
  365. // If the field is translatable only on certain bundles, there will be a join
  366. // on langcode OR bundle name.
  367. elseif (!empty($translatable_configs) && !empty($untranslatable_configs)) {
  368. foreach ($untranslatable_configs as $config) {
  369. $untranslatable_config_bundles[] = $config->getTargetBundle();
  370. }
  371. $translation_join_type = 'language_bundle';
  372. }
  373. // Build the relationships between the field table and the entity tables.
  374. $table_alias = $field_tables[EntityStorageInterface::FIELD_LOAD_CURRENT]['alias'];
  375. if ($data_table) {
  376. // Tell Views how to join to the base table, via the data table.
  377. $data[$table_alias]['table']['join'][$data_table] = [
  378. 'table' => $table_mapping->getDedicatedDataTableName($field_storage),
  379. 'left_field' => $entity_type->getKey('id'),
  380. 'field' => 'entity_id',
  381. 'extra' => [
  382. ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
  383. ],
  384. ];
  385. }
  386. else {
  387. // If there is no data table, just join directly.
  388. $data[$table_alias]['table']['join'][$base_table] = [
  389. 'table' => $table_mapping->getDedicatedDataTableName($field_storage),
  390. 'left_field' => $entity_type->getKey('id'),
  391. 'field' => 'entity_id',
  392. 'extra' => [
  393. ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
  394. ],
  395. ];
  396. }
  397. if ($translation_join_type === 'language_bundle') {
  398. $data[$table_alias]['table']['join'][$data_table]['join_id'] = 'field_or_language_join';
  399. $data[$table_alias]['table']['join'][$data_table]['extra'][] = [
  400. 'left_field' => 'langcode',
  401. 'field' => 'langcode',
  402. ];
  403. $data[$table_alias]['table']['join'][$data_table]['extra'][] = [
  404. 'field' => 'bundle',
  405. 'value' => $untranslatable_config_bundles,
  406. ];
  407. }
  408. elseif ($translation_join_type === 'language') {
  409. $data[$table_alias]['table']['join'][$data_table]['extra'][] = [
  410. 'left_field' => 'langcode',
  411. 'field' => 'langcode',
  412. ];
  413. }
  414. if ($supports_revisions) {
  415. $table_alias = $field_tables[EntityStorageInterface::FIELD_LOAD_REVISION]['alias'];
  416. if ($entity_revision_data_table) {
  417. // Tell Views how to join to the revision table, via the data table.
  418. $data[$table_alias]['table']['join'][$entity_revision_data_table] = [
  419. 'table' => $table_mapping->getDedicatedRevisionTableName($field_storage),
  420. 'left_field' => $entity_type->getKey('revision'),
  421. 'field' => 'revision_id',
  422. 'extra' => [
  423. ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
  424. ],
  425. ];
  426. }
  427. else {
  428. // If there is no data table, just join directly.
  429. $data[$table_alias]['table']['join'][$entity_revision_table] = [
  430. 'table' => $table_mapping->getDedicatedRevisionTableName($field_storage),
  431. 'left_field' => $entity_type->getKey('revision'),
  432. 'field' => 'revision_id',
  433. 'extra' => [
  434. ['field' => 'deleted', 'value' => 0, 'numeric' => TRUE],
  435. ],
  436. ];
  437. }
  438. if ($translation_join_type === 'language_bundle') {
  439. $data[$table_alias]['table']['join'][$entity_revision_data_table]['join_id'] = 'field_or_language_join';
  440. $data[$table_alias]['table']['join'][$entity_revision_data_table]['extra'][] = [
  441. 'left_field' => 'langcode',
  442. 'field' => 'langcode',
  443. ];
  444. $data[$table_alias]['table']['join'][$entity_revision_data_table]['extra'][] = [
  445. 'value' => $untranslatable_config_bundles,
  446. 'field' => 'bundle',
  447. ];
  448. }
  449. elseif ($translation_join_type === 'language') {
  450. $data[$table_alias]['table']['join'][$entity_revision_data_table]['extra'][] = [
  451. 'left_field' => 'langcode',
  452. 'field' => 'langcode',
  453. ];
  454. }
  455. }
  456. $group_name = $entity_type->getLabel();
  457. // Get the list of bundles the field appears in.
  458. $bundles_names = $field_storage->getBundles();
  459. // Build the list of additional fields to add to queries.
  460. $add_fields = ['delta', 'langcode', 'bundle'];
  461. foreach (array_keys($field_columns) as $column) {
  462. $add_fields[] = $table_mapping->getFieldColumnName($field_storage, $column);
  463. }
  464. // Determine the label to use for the field. We don't have a label available
  465. // at the field level, so we just go through all fields and take the one
  466. // which is used the most frequently.
  467. list($label, $all_labels) = views_entity_field_label($entity_type_id, $field_name);
  468. // Expose data for the field as a whole.
  469. foreach ($field_tables as $type => $table_info) {
  470. $table = $table_info['table'];
  471. $table_alias = $table_info['alias'];
  472. if ($type == EntityStorageInterface::FIELD_LOAD_CURRENT) {
  473. $group = $group_name;
  474. $field_alias = $field_name;
  475. }
  476. else {
  477. $group = t('@group (historical data)', ['@group' => $group_name]);
  478. $field_alias = $field_name . '-revision_id';
  479. }
  480. $data[$table_alias][$field_alias] = [
  481. 'group' => $group,
  482. 'title' => $label,
  483. 'title short' => $label,
  484. 'help' => t('Appears in: @bundles.', ['@bundles' => implode(', ', $bundles_names)]),
  485. ];
  486. // Go through and create a list of aliases for all possible combinations of
  487. // entity type + name.
  488. $aliases = [];
  489. $also_known = [];
  490. foreach ($all_labels as $label_name => $true) {
  491. if ($type == EntityStorageInterface::FIELD_LOAD_CURRENT) {
  492. if ($label != $label_name) {
  493. $aliases[] = [
  494. 'base' => $base_table,
  495. 'group' => $group_name,
  496. 'title' => $label_name,
  497. 'help' => t('This is an alias of @group: @field.', ['@group' => $group_name, '@field' => $label]),
  498. ];
  499. $also_known[] = t('@group: @field', ['@group' => $group_name, '@field' => $label_name]);
  500. }
  501. }
  502. elseif ($supports_revisions && $label != $label_name) {
  503. $aliases[] = [
  504. 'base' => $table,
  505. 'group' => t('@group (historical data)', ['@group' => $group_name]),
  506. 'title' => $label_name,
  507. 'help' => t('This is an alias of @group: @field.', ['@group' => $group_name, '@field' => $label]),
  508. ];
  509. $also_known[] = t('@group (historical data): @field', ['@group' => $group_name, '@field' => $label_name]);
  510. }
  511. }
  512. if ($aliases) {
  513. $data[$table_alias][$field_alias]['aliases'] = $aliases;
  514. // The $also_known variable contains markup that is HTML escaped and that
  515. // loses safeness when imploded. The help text is used in #description
  516. // and therefore XSS admin filtered by default. Escaped HTML is not
  517. // altered by XSS filtering, therefore it is safe to just concatenate the
  518. // strings. Afterwards we mark the entire string as safe, so it won't be
  519. // escaped, no matter where it is used.
  520. // Considering the dual use of this help data (both as metadata and as
  521. // help text), other patterns such as use of #markup would not be correct
  522. // here.
  523. $data[$table_alias][$field_alias]['help'] = Markup::create($data[$table_alias][$field_alias]['help'] . ' ' . t('Also known as:') . ' ' . implode(', ', $also_known));
  524. }
  525. $keys = array_keys($field_columns);
  526. $real_field = reset($keys);
  527. $data[$table_alias][$field_alias]['field'] = [
  528. 'table' => $table,
  529. 'id' => 'field',
  530. 'field_name' => $field_name,
  531. 'entity_type' => $entity_type_id,
  532. // Provide a real field for group by.
  533. 'real field' => $field_alias . '_' . $real_field,
  534. 'additional fields' => $add_fields,
  535. // Default the element type to div, let the UI change it if necessary.
  536. 'element type' => 'div',
  537. 'is revision' => $type == EntityStorageInterface::FIELD_LOAD_REVISION,
  538. ];
  539. }
  540. // Expose data for each field property individually.
  541. foreach ($field_columns as $column => $attributes) {
  542. $allow_sort = TRUE;
  543. // Identify likely filters and arguments for each column based on field type.
  544. switch ($attributes['type']) {
  545. case 'int':
  546. case 'mediumint':
  547. case 'tinyint':
  548. case 'bigint':
  549. case 'serial':
  550. case 'numeric':
  551. case 'float':
  552. $filter = 'numeric';
  553. $argument = 'numeric';
  554. $sort = 'standard';
  555. if ($field_storage->getType() == 'boolean') {
  556. $filter = 'boolean';
  557. }
  558. break;
  559. case 'blob':
  560. // It does not make sense to sort by blob.
  561. $allow_sort = FALSE;
  562. default:
  563. $filter = 'string';
  564. $argument = 'string';
  565. $sort = 'standard';
  566. break;
  567. }
  568. if (count($field_columns) == 1 || $column == 'value') {
  569. $title = t('@label (@name)', ['@label' => $label, '@name' => $field_name]);
  570. $title_short = $label;
  571. }
  572. else {
  573. $title = t('@label (@name:@column)', ['@label' => $label, '@name' => $field_name, '@column' => $column]);
  574. $title_short = t('@label:@column', ['@label' => $label, '@column' => $column]);
  575. }
  576. // Expose data for the property.
  577. foreach ($field_tables as $type => $table_info) {
  578. $table = $table_info['table'];
  579. $table_alias = $table_info['alias'];
  580. if ($type == EntityStorageInterface::FIELD_LOAD_CURRENT) {
  581. $group = $group_name;
  582. }
  583. else {
  584. $group = t('@group (historical data)', ['@group' => $group_name]);
  585. }
  586. $column_real_name = $table_mapping->getFieldColumnName($field_storage, $column);
  587. // Load all the fields from the table by default.
  588. $additional_fields = $table_mapping->getAllColumns($table);
  589. $data[$table_alias][$column_real_name] = [
  590. 'group' => $group,
  591. 'title' => $title,
  592. 'title short' => $title_short,
  593. 'help' => t('Appears in: @bundles.', ['@bundles' => implode(', ', $bundles_names)]),
  594. ];
  595. // Go through and create a list of aliases for all possible combinations of
  596. // entity type + name.
  597. $aliases = [];
  598. $also_known = [];
  599. foreach ($all_labels as $label_name => $true) {
  600. if ($label != $label_name) {
  601. if (count($field_columns) == 1 || $column == 'value') {
  602. $alias_title = t('@label (@name)', ['@label' => $label_name, '@name' => $field_name]);
  603. }
  604. else {
  605. $alias_title = t('@label (@name:@column)', ['@label' => $label_name, '@name' => $field_name, '@column' => $column]);
  606. }
  607. $aliases[] = [
  608. 'group' => $group_name,
  609. 'title' => $alias_title,
  610. 'help' => t('This is an alias of @group: @field.', ['@group' => $group_name, '@field' => $title]),
  611. ];
  612. $also_known[] = t('@group: @field', ['@group' => $group_name, '@field' => $title]);
  613. }
  614. }
  615. if ($aliases) {
  616. $data[$table_alias][$column_real_name]['aliases'] = $aliases;
  617. // The $also_known variable contains markup that is HTML escaped and
  618. // that loses safeness when imploded. The help text is used in
  619. // #description and therefore XSS admin filtered by default. Escaped
  620. // HTML is not altered by XSS filtering, therefore it is safe to just
  621. // concatenate the strings. Afterwards we mark the entire string as
  622. // safe, so it won't be escaped, no matter where it is used.
  623. // Considering the dual use of this help data (both as metadata and as
  624. // help text), other patterns such as use of #markup would not be
  625. // correct here.
  626. $data[$table_alias][$column_real_name]['help'] = Markup::create($data[$table_alias][$column_real_name]['help'] . ' ' . t('Also known as:') . ' ' . implode(', ', $also_known));
  627. }
  628. $data[$table_alias][$column_real_name]['argument'] = [
  629. 'field' => $column_real_name,
  630. 'table' => $table,
  631. 'id' => $argument,
  632. 'additional fields' => $additional_fields,
  633. 'field_name' => $field_name,
  634. 'entity_type' => $entity_type_id,
  635. 'empty field name' => t('- No value -'),
  636. ];
  637. $data[$table_alias][$column_real_name]['filter'] = [
  638. 'field' => $column_real_name,
  639. 'table' => $table,
  640. 'id' => $filter,
  641. 'additional fields' => $additional_fields,
  642. 'field_name' => $field_name,
  643. 'entity_type' => $entity_type_id,
  644. 'allow empty' => TRUE,
  645. ];
  646. if (!empty($allow_sort)) {
  647. $data[$table_alias][$column_real_name]['sort'] = [
  648. 'field' => $column_real_name,
  649. 'table' => $table,
  650. 'id' => $sort,
  651. 'additional fields' => $additional_fields,
  652. 'field_name' => $field_name,
  653. 'entity_type' => $entity_type_id,
  654. ];
  655. }
  656. // Set click sortable if there is a field definition.
  657. if (isset($data[$table_alias][$field_name]['field'])) {
  658. $data[$table_alias][$field_name]['field']['click sortable'] = $allow_sort;
  659. }
  660. // Expose additional delta column for multiple value fields.
  661. if ($field_storage->isMultiple()) {
  662. $title_delta = t('@label (@name:delta)', ['@label' => $label, '@name' => $field_name]);
  663. $title_short_delta = t('@label:delta', ['@label' => $label]);
  664. $data[$table_alias]['delta'] = [
  665. 'group' => $group,
  666. 'title' => $title_delta,
  667. 'title short' => $title_short_delta,
  668. 'help' => t('Delta - Appears in: @bundles.', ['@bundles' => implode(', ', $bundles_names)]),
  669. ];
  670. $data[$table_alias]['delta']['field'] = [
  671. 'id' => 'numeric',
  672. ];
  673. $data[$table_alias]['delta']['argument'] = [
  674. 'field' => 'delta',
  675. 'table' => $table,
  676. 'id' => 'numeric',
  677. 'additional fields' => $additional_fields,
  678. 'empty field name' => t('- No value -'),
  679. 'field_name' => $field_name,
  680. 'entity_type' => $entity_type_id,
  681. ];
  682. $data[$table_alias]['delta']['filter'] = [
  683. 'field' => 'delta',
  684. 'table' => $table,
  685. 'id' => 'numeric',
  686. 'additional fields' => $additional_fields,
  687. 'field_name' => $field_name,
  688. 'entity_type' => $entity_type_id,
  689. 'allow empty' => TRUE,
  690. ];
  691. $data[$table_alias]['delta']['sort'] = [
  692. 'field' => 'delta',
  693. 'table' => $table,
  694. 'id' => 'standard',
  695. 'additional fields' => $additional_fields,
  696. 'field_name' => $field_name,
  697. 'entity_type' => $entity_type_id,
  698. ];
  699. }
  700. }
  701. }
  702. return $data;
  703. }
  704. /**
  705. * Implements hook_field_views_data().
  706. *
  707. * The function implements the hook in behalf of 'core' because it adds a
  708. * relationship and a reverse relationship to entity_reference field type, which
  709. * is provided by core.
  710. */
  711. function core_field_views_data(FieldStorageConfigInterface $field_storage) {
  712. $data = views_field_default_views_data($field_storage);
  713. // The code below only deals with the Entity reference field type.
  714. if ($field_storage->getType() != 'entity_reference') {
  715. return $data;
  716. }
  717. $entity_type_manager = \Drupal::entityTypeManager();
  718. $entity_type_id = $field_storage->getTargetEntityTypeId();
  719. /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
  720. $table_mapping = $entity_type_manager->getStorage($entity_type_id)->getTableMapping();
  721. foreach ($data as $table_name => $table_data) {
  722. // Add a relationship to the target entity type.
  723. $target_entity_type_id = $field_storage->getSetting('target_type');
  724. $target_entity_type = $entity_type_manager->getDefinition($target_entity_type_id);
  725. $entity_type_id = $field_storage->getTargetEntityTypeId();
  726. $entity_type = $entity_type_manager->getDefinition($entity_type_id);
  727. $target_base_table = $target_entity_type->getDataTable() ?: $target_entity_type->getBaseTable();
  728. $field_name = $field_storage->getName();
  729. // Provide a relationship for the entity type with the entity reference
  730. // field.
  731. $args = [
  732. '@label' => $target_entity_type->getLabel(),
  733. '@field_name' => $field_name,
  734. ];
  735. $data[$table_name][$field_name]['relationship'] = [
  736. 'title' => t('@label referenced from @field_name', $args),
  737. 'label' => t('@field_name: @label', $args),
  738. 'group' => $entity_type->getLabel(),
  739. 'help' => t('Appears in: @bundles.', ['@bundles' => implode(', ', $field_storage->getBundles())]),
  740. 'id' => 'standard',
  741. 'base' => $target_base_table,
  742. 'entity type' => $target_entity_type_id,
  743. 'base field' => $target_entity_type->getKey('id'),
  744. 'relationship field' => $field_name . '_target_id',
  745. ];
  746. // Provide a reverse relationship for the entity type that is referenced by
  747. // the field.
  748. $args['@entity'] = $entity_type->getLabel();
  749. $args['@label'] = $target_entity_type->getSingularLabel();
  750. $pseudo_field_name = 'reverse__' . $entity_type_id . '__' . $field_name;
  751. $data[$target_base_table][$pseudo_field_name]['relationship'] = [
  752. 'title' => t('@entity using @field_name', $args),
  753. 'label' => t('@field_name', ['@field_name' => $field_name]),
  754. 'group' => $target_entity_type->getLabel(),
  755. 'help' => t('Relate each @entity with a @field_name set to the @label.', $args),
  756. 'id' => 'entity_reverse',
  757. 'base' => $entity_type->getDataTable() ?: $entity_type->getBaseTable(),
  758. 'entity_type' => $entity_type_id,
  759. 'base field' => $entity_type->getKey('id'),
  760. 'field_name' => $field_name,
  761. 'field table' => $table_mapping->getDedicatedDataTableName($field_storage),
  762. 'field field' => $field_name . '_target_id',
  763. 'join_extra' => [
  764. [
  765. 'field' => 'deleted',
  766. 'value' => 0,
  767. 'numeric' => TRUE,
  768. ],
  769. ],
  770. ];
  771. }
  772. return $data;
  773. }