Drupal investigation

field.module 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. /**
  3. * @file
  4. * Attach custom data fields to Drupal entities.
  5. */
  6. use Drupal\Core\Config\ConfigImporter;
  7. use Drupal\Core\Entity\EntityTypeInterface;
  8. use Drupal\Core\Entity\DynamicallyFieldableEntityStorageInterface;
  9. use Drupal\field\ConfigImporterFieldPurger;
  10. use Drupal\field\Entity\FieldConfig;
  11. use Drupal\field\Entity\FieldStorageConfig;
  12. use Drupal\field\FieldConfigInterface;
  13. use Drupal\field\FieldStorageConfigInterface;
  14. use Drupal\Core\Form\FormStateInterface;
  15. use Drupal\Core\Routing\RouteMatchInterface;
  16. use Drupal\Core\Url;
  17. /*
  18. * Load all public Field API functions. Drupal currently has no
  19. * mechanism for auto-loading core APIs, so we have to load them on
  20. * every page request.
  21. */
  22. require_once __DIR__ . '/field.purge.inc';
  23. /**
  24. * @defgroup field Field API
  25. * @{
  26. * Attaches custom data fields to Drupal entities.
  27. *
  28. * The Field API allows custom data fields to be attached to Drupal entities and
  29. * takes care of storing, loading, editing, and rendering field data. Any entity
  30. * type (node, user, etc.) can use the Field API to make itself "fieldable" and
  31. * thus allow fields to be attached to it. Other modules can provide a user
  32. * interface for managing custom fields via a web browser as well as a wide and
  33. * flexible variety of data type, form element, and display format capabilities.
  34. *
  35. * The Field API defines two primary data structures, FieldStorage and Field,
  36. * and the concept of a Bundle. A FieldStorage defines a particular type of data
  37. * that can be attached to entities. A Field is attached to a single
  38. * Bundle. A Bundle is a set of fields that are treated as a group by the Field
  39. * Attach API and is related to a single fieldable entity type.
  40. *
  41. * For example, suppose a site administrator wants Article nodes to have a
  42. * subtitle and photo. Using the Field API or Field UI module, the administrator
  43. * creates a field named 'subtitle' of type 'text' and a field named 'photo' of
  44. * type 'image'. The administrator (again, via a UI) creates two Field
  45. * Instances, one attaching the field 'subtitle' to the 'node' bundle 'article'
  46. * and one attaching the field 'photo' to the 'node' bundle 'article'. When the
  47. * node storage loads an Article node, it loads the values of the
  48. * 'subtitle' and 'photo' fields because they are both attached to the 'node'
  49. * bundle 'article'.
  50. *
  51. * - @link field_types Field Types API @endlink: Defines field types, widget
  52. * types, and display formatters. Field modules use this API to provide field
  53. * types like Text and Node Reference along with the associated form elements
  54. * and display formatters.
  55. *
  56. * - @link field_purge Field API bulk data deletion @endlink: Cleans up after
  57. * bulk deletion operations such as deletion of field storage or field.
  58. */
  59. /**
  60. * Implements hook_help().
  61. */
  62. function field_help($route_name, RouteMatchInterface $route_match) {
  63. switch ($route_name) {
  64. case 'help.page.field':
  65. $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
  66. $output = '';
  67. $output .= '<h3>' . t('About') . '</h3>';
  68. $output .= '<p>' . t('The Field module allows custom data fields to be defined for <em>entity</em> types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the <a href=":field-ui-help">Field UI module</a> user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the <a href=":field">online documentation for the Field module</a>.', [':field-ui-help' => $field_ui_url, ':field' => 'https://www.drupal.org/documentation/modules/field']) . '</p>';
  69. $output .= '<h3>' . t('Terminology') . '</h3>';
  70. $output .= '<dl>';
  71. $output .= '<dt>' . t('Entities and entity types') . '</dt>';
  72. $output .= '<dd>' . t('The website\'s content and configuration is managed using <em>entities</em>, which are grouped into <em>entity types</em>. <em>Content entity types</em> are the entity types for site content (such as the main site content, comments, custom blocks, taxonomy terms, and user accounts). <em>Configuration entity types</em> are used to store configuration information for your site, such as individual views in the Views module, and settings for your main site content types.') . '</dd>';
  73. $output .= '<dt>' . t('Entity sub-types') . '</dt>';
  74. $output .= '<dd>' . t('Some content entity types are further grouped into sub-types (for example, you could have article and page content types within the main site content entity type, and tag and category vocabularies within the taxonomy term entity type); other entity types, such as user accounts, do not have sub-types. Programmers use the term <em>bundle</em> for entity sub-types.') . '</dd>';
  75. $output .= '<dt>' . t('Fields and field types') . '</dt>';
  76. $output .= '<dd>' . t('Content entity types and sub-types store most of their text, file, and other information in <em>fields</em>. Fields are grouped by <em>field type</em>; field types define what type of data can be stored in that field, such as text, images, or taxonomy term references.') . '</dd>';
  77. $output .= '<dt>' . t('Formatters and view modes') . '</dd>';
  78. $output .= '<dd>' . t('Content entity types and sub-types can have one or more <em>view modes</em>, used for displaying the entity items. For instance, a content item could be viewed in full content mode on its own page, teaser mode in a list, or RSS mode in a feed. In each view mode, each field can be hidden or displayed, and if it is displayed, you can choose and configure the <em>formatter</em> that is used to display the field. For instance, a long text field can be displayed trimmed or full-length, and taxonomy term reference fields can be displayed in plain text or linked to the taxonomy term page.') . '</dd>';
  79. $output .= '<dt>' . t('Widgets and form modes') . '</dd>';
  80. $output .= '<dd>' . t('Content entity types and sub-types can have one or more <em>form modes</em>, used for editing. For instance, a content item could be edited in a compact format with only some fields editable, or a full format that allows all fields to be edited. In each form mode, each field can be hidden or displayed, and if it is displayed, you can choose and configure the <em>widget</em> that is used to edit the field. For instance, a taxonomy term reference field can be edited using a select list, radio buttons, or an autocomplete widget.') . '</dd>';
  81. $output .= '</dl>';
  82. $output .= '<h3>' . t('Uses') . '</h3>';
  83. $output .= '<dl>';
  84. $output .= '<dt>' . t('Enabling field types, widgets, and formatters') . '</dt>';
  85. $output .= '<dd>' . t('The Field module provides the infrastructure for fields; the field types, formatters, and widgets are provided by Drupal core or additional modules. Some of the modules are required; the optional modules can be enabled from the <a href=":modules">Extend administration page</a>. Additional fields, formatters, and widgets may be provided by contributed modules, which you can find in the <a href=":contrib">contributed module section of Drupal.org</a>.', [':modules' => \Drupal::url('system.modules_list'), ':contrib' => 'https://www.drupal.org/project/modules']) . '</dd>';
  86. $output .= '<h3>' . t('Field, widget, and formatter information') . '</h3>';
  87. // Make a list of all widget, formatter, and field modules currently
  88. // enabled, ordered by displayed module name (module names are not
  89. // translated).
  90. $items = [];
  91. $modules = \Drupal::moduleHandler()->getModuleList();
  92. $widgets = \Drupal::service('plugin.manager.field.widget')->getDefinitions();
  93. $field_types = \Drupal::service('plugin.manager.field.field_type')->getUiDefinitions();
  94. $formatters = \Drupal::service('plugin.manager.field.formatter')->getDefinitions();
  95. $providers = [];
  96. foreach (array_merge($field_types, $widgets, $formatters) as $plugin) {
  97. $providers[] = $plugin['provider'];
  98. }
  99. $providers = array_unique($providers);
  100. sort($providers);
  101. foreach ($providers as $provider) {
  102. // Skip plugins provided by core components as they do not implement
  103. // hook_help().
  104. if (isset($modules[$provider])) {
  105. $display = \Drupal::moduleHandler()->getName($provider);
  106. if (\Drupal::moduleHandler()->implementsHook($provider, 'help')) {
  107. $items[] = \Drupal::l($display, new Url('help.page', ['name' => $provider]));
  108. }
  109. else {
  110. $items[] = $display;
  111. }
  112. }
  113. }
  114. if ($items) {
  115. $output .= '<dt>' . t('Provided by modules') . '</dt>';
  116. $output .= '<dd>' . t('Here is a list of the currently enabled field, formatter, and widget modules:');
  117. $item_list = [
  118. '#theme' => 'item_list',
  119. '#items' => $items,
  120. ];
  121. $output .= \Drupal::service('renderer')->renderPlain($item_list);
  122. $output .= '</dd>';
  123. }
  124. $output .= '<dt>' . t('Provided by Drupal core') . '</dt>';
  125. $output .= '<dd>' . t('As mentioned previously, some field types, widgets, and formatters are provided by Drupal core. Here are some notes on how to use some of these:');
  126. $output .= '<ul>';
  127. $output .= '<li><p>' . t('<strong>Entity Reference</strong> fields allow you to create fields that contain links to other entities (such as content items, taxonomy terms, etc.) within the site. This allows you, for example, to include a link to a user within a content item. For more information, see <a href=":er_do">the online documentation for the Entity Reference module</a>.', [':er_do' => 'https://drupal.org/documentation/modules/entityreference']) . '</p>';
  128. $output .= '<dl>';
  129. $output .= '<dt>' . t('Managing and displaying entity reference fields') . '</dt>';
  130. $output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the entity reference field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => $field_ui_url]) . '</dd>';
  131. $output .= '<dt>' . t('Selecting reference type') . '</dt>';
  132. $output .= '<dd>' . t('In the field settings you can select which entity type you want to create a reference to.') . '</dd>';
  133. $output .= '<dt>' . t('Filtering and sorting reference fields') . '</dt>';
  134. $output .= '<dd>' . t('Depending on the chosen entity type, additional filtering and sorting options are available for the list of entities that can be referred to, in the field settings. For example, the list of users can be filtered by role and sorted by name or ID.') . '</dd>';
  135. $output .= '<dt>' . t('Displaying a reference') . '</dt>';
  136. $output .= '<dd>' . t('An entity reference can be displayed as a simple label with or without a link to the entity. Alternatively, the referenced entity can be displayed as a teaser (or any other available view mode) inside the referencing entity.') . '</dd>';
  137. $output .= '<dt>' . t('Configuring form displays') . '</dt>';
  138. $output .= '<dd>' . t('Reference fields have several widgets available on the <em>Manage form display</em> page:');
  139. $output .= '<ul>';
  140. $output .= '<li>' . t('The <em>Check boxes/radio buttons</em> widget displays the existing entities for the entity type as check boxes or radio buttons based on the <em>Allowed number of values</em> set for the field.') . '</li>';
  141. $output .= '<li>' . t('The <em>Select list</em> widget displays the existing entities in a drop-down list or scrolling list box based on the <em>Allowed number of values</em> setting for the field.') . '</li>';
  142. $output .= '<li>' . t('The <em>Autocomplete</em> widget displays text fields in which users can type entity labels based on the <em>Allowed number of values</em>. The widget can be configured to display all entities that contain the typed characters or restricted to those starting with those characters.') . '</li>';
  143. $output .= '<li>' . t('The <em>Autocomplete (Tags style)</em> widget displays a multi-text field in which users can type in a comma-separated list of entity labels.') . '</li>';
  144. $output .= '</ul></dd>';
  145. $output .= '</dl></li>';
  146. $output .= '<li>' . t('<strong>Number fields</strong>: When you add a number field you can choose from three types: <em>decimal</em>, <em>float</em>, and <em>integer</em>. The <em>decimal</em> number field type allows users to enter exact decimal values, with fixed numbers of decimal places. The <em>float</em> number field type allows users to enter approximate decimal values. The <em>integer</em> number field type allows users to enter whole numbers, such as years (for example, 2012) or values (for example, 1, 2, 5, 305). It does not allow decimals.') . '</li>';
  147. $output .= '</ul></dd>';
  148. $output .= '</dl>';
  149. return $output;
  150. }
  151. }
  152. /**
  153. * Implements hook_cron().
  154. */
  155. function field_cron() {
  156. // Do a pass of purging on deleted Field API data, if any exists.
  157. $limit = \Drupal::config('field.settings')->get('purge_batch_size');
  158. field_purge_batch($limit);
  159. }
  160. /**
  161. * Implements hook_entity_field_storage_info().
  162. */
  163. function field_entity_field_storage_info(EntityTypeInterface $entity_type) {
  164. if (\Drupal::entityManager()->getStorage($entity_type->id()) instanceof DynamicallyFieldableEntityStorageInterface) {
  165. // Query by filtering on the ID as this is more efficient than filtering
  166. // on the entity_type property directly.
  167. $ids = \Drupal::entityQuery('field_storage_config')
  168. ->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
  169. ->execute();
  170. // Fetch all fields and key them by field name.
  171. $field_storages = FieldStorageConfig::loadMultiple($ids);
  172. $result = [];
  173. foreach ($field_storages as $field_storage) {
  174. $result[$field_storage->getName()] = $field_storage;
  175. }
  176. return $result;
  177. }
  178. }
  179. /**
  180. * Implements hook_entity_bundle_field_info().
  181. */
  182. function field_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  183. if (\Drupal::entityManager()->getStorage($entity_type->id()) instanceof DynamicallyFieldableEntityStorageInterface) {
  184. // Query by filtering on the ID as this is more efficient than filtering
  185. // on the entity_type property directly.
  186. $ids = \Drupal::entityQuery('field_config')
  187. ->condition('id', $entity_type->id() . '.' . $bundle . '.', 'STARTS_WITH')
  188. ->execute();
  189. // Fetch all fields and key them by field name.
  190. $field_configs = FieldConfig::loadMultiple($ids);
  191. $result = [];
  192. foreach ($field_configs as $field_instance) {
  193. $result[$field_instance->getName()] = $field_instance;
  194. }
  195. return $result;
  196. }
  197. }
  198. /**
  199. * Implements hook_entity_bundle_delete().
  200. */
  201. function field_entity_bundle_delete($entity_type_id, $bundle) {
  202. $storage = \Drupal::entityManager()->getStorage('field_config');
  203. // Get the fields on the bundle.
  204. $fields = $storage->loadByProperties(['entity_type' => $entity_type_id, 'bundle' => $bundle]);
  205. // This deletes the data for the field as well as the field themselves. This
  206. // function actually just marks the data and fields as deleted, leaving the
  207. // garbage collection for a separate process, because it is not always
  208. // possible to delete this much data in a single page request (particularly
  209. // since for some field types, the deletion is more than just a simple DELETE
  210. // query).
  211. foreach ($fields as $field) {
  212. $field->delete();
  213. }
  214. // We are duplicating the work done by
  215. // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::onDependencyRemoval()
  216. // because we need to take into account bundles that are not provided by a
  217. // config entity type so they are not part of the config dependencies.
  218. // Gather a list of all entity reference fields.
  219. $map = \Drupal::entityManager()->getFieldMapByFieldType('entity_reference');
  220. $ids = [];
  221. foreach ($map as $type => $info) {
  222. foreach ($info as $name => $data) {
  223. foreach ($data['bundles'] as $bundle_name) {
  224. $ids[] = "$type.$bundle_name.$name";
  225. }
  226. }
  227. }
  228. // Update the 'target_bundles' handler setting if needed.
  229. foreach (FieldConfig::loadMultiple($ids) as $field_config) {
  230. if ($field_config->getSetting('target_type') == $entity_type_id) {
  231. $handler_settings = $field_config->getSetting('handler_settings');
  232. if (isset($handler_settings['target_bundles'][$bundle])) {
  233. unset($handler_settings['target_bundles'][$bundle]);
  234. $field_config->setSetting('handler_settings', $handler_settings);
  235. $field_config->save();
  236. // In case we deleted the only target bundle allowed by the field we
  237. // have to log a critical message because the field will not function
  238. // correctly anymore.
  239. if ($handler_settings['target_bundles'] === []) {
  240. \Drupal::logger('entity_reference')->critical('The %target_bundle bundle (entity type: %target_entity_type) was deleted. As a result, the %field_name entity reference field (entity_type: %entity_type, bundle: %bundle) no longer has any valid bundle it can reference. The field is not working correctly anymore and has to be adjusted.', [
  241. '%target_bundle' => $bundle,
  242. '%target_entity_type' => $entity_type_id,
  243. '%field_name' => $field_config->getName(),
  244. '%entity_type' => $field_config->getTargetEntityTypeId(),
  245. '%bundle' => $field_config->getTargetBundle()
  246. ]);
  247. }
  248. }
  249. }
  250. }
  251. }
  252. /**
  253. * @} End of "defgroup field".
  254. */
  255. /**
  256. * Assembles a partial entity structure with initial IDs.
  257. *
  258. * @param object $ids
  259. * An object with the properties entity_type (required), entity_id (required),
  260. * revision_id (optional) and bundle (optional).
  261. *
  262. * @return \Drupal\Core\Entity\EntityInterface
  263. * An entity, initialized with the provided IDs.
  264. */
  265. function _field_create_entity_from_ids($ids) {
  266. $id_properties = [];
  267. $entity_type = \Drupal::entityManager()->getDefinition($ids->entity_type);
  268. if ($id_key = $entity_type->getKey('id')) {
  269. $id_properties[$id_key] = $ids->entity_id;
  270. }
  271. if (isset($ids->revision_id) && $revision_key = $entity_type->getKey('revision')) {
  272. $id_properties[$revision_key] = $ids->revision_id;
  273. }
  274. if (isset($ids->bundle) && $bundle_key = $entity_type->getKey('bundle')) {
  275. $id_properties[$bundle_key] = $ids->bundle;
  276. }
  277. return \Drupal::entityTypeManager()
  278. ->getStorage($ids->entity_type)
  279. ->create($id_properties);
  280. }
  281. /**
  282. * Implements hook_config_import_steps_alter().
  283. */
  284. function field_config_import_steps_alter(&$sync_steps, ConfigImporter $config_importer) {
  285. $field_storages = ConfigImporterFieldPurger::getFieldStoragesToPurge(
  286. $config_importer->getStorageComparer()->getSourceStorage()->read('core.extension'),
  287. $config_importer->getStorageComparer()->getChangelist('delete')
  288. );
  289. if ($field_storages) {
  290. // Add a step to the beginning of the configuration synchronization process
  291. // to purge field data where the module that provides the field is being
  292. // uninstalled.
  293. array_unshift($sync_steps, ['\Drupal\field\ConfigImporterFieldPurger', 'process']);
  294. };
  295. }
  296. /**
  297. * Implements hook_form_FORM_ID_alter().
  298. *
  299. * Adds a warning if field data will be permanently removed by the configuration
  300. * synchronization.
  301. *
  302. * @see \Drupal\field\ConfigImporterFieldPurger
  303. */
  304. function field_form_config_admin_import_form_alter(&$form, FormStateInterface $form_state) {
  305. // Only display the message when there is a storage comparer available and the
  306. // form is not submitted.
  307. $user_input = $form_state->getUserInput();
  308. $storage_comparer = $form_state->get('storage_comparer');
  309. if ($storage_comparer && empty($user_input)) {
  310. $field_storages = ConfigImporterFieldPurger::getFieldStoragesToPurge(
  311. $storage_comparer->getSourceStorage()->read('core.extension'),
  312. $storage_comparer->getChangelist('delete')
  313. );
  314. if ($field_storages) {
  315. foreach ($field_storages as $field) {
  316. $field_labels[] = $field->label();
  317. }
  318. drupal_set_message(\Drupal::translation()->formatPlural(
  319. count($field_storages),
  320. 'This synchronization will delete data from the field %fields.',
  321. 'This synchronization will delete data from the fields: %fields.',
  322. ['%fields' => implode(', ', $field_labels)]
  323. ), 'warning');
  324. }
  325. }
  326. }
  327. /**
  328. * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
  329. *
  330. * Reset the field handler settings, when the storage target_type is changed on
  331. * an entity reference field.
  332. */
  333. function field_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
  334. if ($field_storage->isSyncing()) {
  335. // Don't change anything during a configuration sync.
  336. return;
  337. }
  338. // Act on all sub-types of the entity_reference field type.
  339. /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
  340. $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
  341. $item_class = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';
  342. $class = $field_type_manager->getPluginClass($field_storage->getType());
  343. if ($class !== $item_class && !is_subclass_of($class, $item_class)) {
  344. return;
  345. }
  346. // If target_type changed, reset the handler in the fields using that storage.
  347. if ($field_storage->getSetting('target_type') !== $field_storage->original->getSetting('target_type')) {
  348. foreach ($field_storage->getBundles() as $bundle) {
  349. $field = FieldConfig::loadByName($field_storage->getTargetEntityTypeId(), $bundle, $field_storage->getName());
  350. // Reset the handler settings. This triggers field_field_config_presave(),
  351. // which will take care of reassigning the handler to the correct
  352. // derivative for the new target_type.
  353. $field->setSetting('handler_settings', []);
  354. $field->save();
  355. }
  356. }
  357. }
  358. /**
  359. * Implements hook_ENTITY_TYPE_presave() for 'field_config'.
  360. *
  361. * Determine the selection handler plugin ID for an entity reference field.
  362. */
  363. function field_field_config_presave(FieldConfigInterface $field) {
  364. // Don't change anything during a configuration sync.
  365. if ($field->isSyncing()) {
  366. return;
  367. }
  368. // Act on all sub-types of the entity_reference field type.
  369. /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
  370. $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
  371. $item_class = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';
  372. $class = $field_type_manager->getPluginClass($field->getType());
  373. if ($class !== $item_class && !is_subclass_of($class, $item_class)) {
  374. return;
  375. }
  376. // Make sure the selection handler plugin is the correct derivative for the
  377. // target entity type.
  378. $target_type = $field->getFieldStorageDefinition()->getSetting('target_type');
  379. $selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
  380. list($current_handler) = explode(':', $field->getSetting('handler'), 2);
  381. $field->setSetting('handler', $selection_manager->getPluginId($target_type, $current_handler));
  382. }