layout_builder.module 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. <?php
  2. /**
  3. * @file
  4. * Provides hook implementations for Layout Builder.
  5. */
  6. use Drupal\Core\Breadcrumb\Breadcrumb;
  7. use Drupal\Core\Cache\CacheableMetadata;
  8. use Drupal\Core\Entity\EntityInterface;
  9. use Drupal\Core\Entity\FieldableEntityInterface;
  10. use Drupal\Core\Form\FormStateInterface;
  11. use Drupal\Core\Link;
  12. use Drupal\Core\Render\Element;
  13. use Drupal\Core\Routing\RouteMatchInterface;
  14. use Drupal\Core\Url;
  15. use Drupal\field\FieldConfigInterface;
  16. use Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay;
  17. use Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplayStorage;
  18. use Drupal\layout_builder\Form\DefaultsEntityForm;
  19. use Drupal\layout_builder\Form\LayoutBuilderEntityViewDisplayForm;
  20. use Drupal\layout_builder\Form\OverridesEntityForm;
  21. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  22. use Drupal\layout_builder\Plugin\Block\ExtraFieldBlock;
  23. use Drupal\layout_builder\InlineBlockEntityOperations;
  24. use Drupal\Core\Session\AccountInterface;
  25. use Drupal\Core\Access\AccessResult;
  26. use Drupal\layout_builder\Plugin\SectionStorage\OverridesSectionStorage;
  27. use Drupal\layout_builder\QuickEditIntegration;
  28. /**
  29. * Implements hook_help().
  30. */
  31. function layout_builder_help($route_name, RouteMatchInterface $route_match) {
  32. // Add help text to the Layout Builder UI.
  33. if ($route_match->getRouteObject()->getOption('_layout_builder')) {
  34. $output = '<p>' . t('This layout builder tool allows you to configure the layout of the main content area.') . '</p>';
  35. if (\Drupal::currentUser()->hasPermission('administer blocks')) {
  36. $output .= '<p>' . t('To manage other areas of the page, use the <a href="@block-ui">block administration page</a>.', ['@block-ui' => Url::fromRoute('block.admin_display')->toString()]) . '</p>';
  37. }
  38. else {
  39. $output .= '<p>' . t('To manage other areas of the page, use the block administration page.') . '</p>';
  40. }
  41. $output .= '<p>' . t('Forms and links inside the content of the layout builder tool have been disabled.') . '</p>';
  42. return $output;
  43. }
  44. switch ($route_name) {
  45. case 'help.page.layout_builder':
  46. $output = '<h3>' . t('About') . '</h3>';
  47. $output .= '<p>' . t('Layout Builder allows you to use layouts to customize how content, custom blocks, and other <a href=":field_help" title="Field module help, with background on content entities">content entities</a> are displayed.', [':field_help' => Url::fromRoute('help.page', ['name' => 'field'])->toString()]) . '</p>';
  48. $output .= '<p>' . t('For more information, see the <a href=":layout-builder-documentation">online documentation for the Layout Builder module</a>.', [':layout-builder-documentation' => 'https://www.drupal.org/docs/8/core/modules/layout-builder']) . '</p>';
  49. $output .= '<h3>' . t('Uses') . '</h3>';
  50. $output .= '<dl>';
  51. $output .= '<dt>' . t('Default layouts') . '</dt>';
  52. $output .= '<dd>' . t('Layout Builder can be selectively enabled on the "Manage Display" page in the <a href=":field_ui">Field UI</a>. This allows you to control the output of each type of display individually. For example, a "Basic page" might have view modes such as Full and Teaser, with each view mode having different layouts selected.', [':field_ui' => Url::fromRoute('help.page', ['name' => 'field_ui'])->toString()]) . '</dd>';
  53. $output .= '<dt>' . t('Overridden layouts') . '</dt>';
  54. $output .= '<dd>' . t('If enabled, each individual content item can have a custom layout. Once the layout for an individual content item is overridden, changes to the Default layout will no longer affect it. Overridden layouts may be reverted to return to matching and being synchronized to their Default layout.') . '</dd>';
  55. $output .= '<dt>' . t('User permissions') . '</dt>';
  56. $output .= '<dd>' . t('The Layout Builder module makes a number of permissions available, which can be set by role on the <a href=":permissions">permissions page</a>. For more information, see the <a href=":layout-builder-permissions">Configuring Layout Builder permissions</a> online documentation.', [
  57. ':permissions' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-layout_builder'])->toString(),
  58. ':layout-builder-permissions' => 'https://www.drupal.org/docs/8/core/modules/layout-builder/configuring-layout-builder-permissions',
  59. ]) . '</dd>';
  60. $output .= '</dl>';
  61. return $output;
  62. }
  63. }
  64. /**
  65. * Implements hook_entity_type_alter().
  66. */
  67. function layout_builder_entity_type_alter(array &$entity_types) {
  68. /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  69. $entity_types['entity_view_display']
  70. ->setClass(LayoutBuilderEntityViewDisplay::class)
  71. ->setStorageClass(LayoutBuilderEntityViewDisplayStorage::class)
  72. ->setFormClass('layout_builder', DefaultsEntityForm::class)
  73. ->setFormClass('edit', LayoutBuilderEntityViewDisplayForm::class);
  74. // Ensure every fieldable entity type has a layout form.
  75. foreach ($entity_types as $entity_type) {
  76. if ($entity_type->entityClassImplements(FieldableEntityInterface::class)) {
  77. $entity_type->setFormClass('layout_builder', OverridesEntityForm::class);
  78. }
  79. }
  80. }
  81. /**
  82. * Implements hook_form_FORM_ID_alter() for \Drupal\field_ui\Form\EntityFormDisplayEditForm.
  83. */
  84. function layout_builder_form_entity_form_display_edit_form_alter(&$form, FormStateInterface $form_state) {
  85. // Hides the Layout Builder field. It is rendered directly in
  86. // \Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::buildMultiple().
  87. unset($form['fields'][OverridesSectionStorage::FIELD_NAME]);
  88. $key = array_search(OverridesSectionStorage::FIELD_NAME, $form['#fields']);
  89. if ($key !== FALSE) {
  90. unset($form['#fields'][$key]);
  91. }
  92. }
  93. /**
  94. * Implements hook_field_config_insert().
  95. */
  96. function layout_builder_field_config_insert(FieldConfigInterface $field_config) {
  97. // Clear the sample entity for this entity type and bundle.
  98. $sample_entity_generator = \Drupal::service('layout_builder.sample_entity_generator');
  99. $sample_entity_generator->delete($field_config->getTargetEntityTypeId(), $field_config->getTargetBundle());
  100. \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
  101. }
  102. /**
  103. * Implements hook_field_config_delete().
  104. */
  105. function layout_builder_field_config_delete(FieldConfigInterface $field_config) {
  106. // Clear the sample entity for this entity type and bundle.
  107. $sample_entity_generator = \Drupal::service('layout_builder.sample_entity_generator');
  108. $sample_entity_generator->delete($field_config->getTargetEntityTypeId(), $field_config->getTargetBundle());
  109. \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
  110. }
  111. /**
  112. * Implements hook_entity_view_alter().
  113. *
  114. * ExtraFieldBlock block plugins add placeholders for each extra field which is
  115. * configured to be displayed. Those placeholders are replaced by this hook.
  116. * Modules that implement hook_entity_extra_field_info() use their
  117. * implementations of hook_entity_view_alter() to add the rendered output of
  118. * the extra fields they provide, so we cannot get the rendered output of extra
  119. * fields before this point in the view process.
  120. * layout_builder_module_implements_alter() moves this implementation of
  121. * hook_entity_view_alter() to the end of the list.
  122. *
  123. * @see \Drupal\layout_builder\Plugin\Block\ExtraFieldBlock::build()
  124. * @see layout_builder_module_implements_alter()
  125. */
  126. function layout_builder_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  127. // Only replace extra fields when Layout Builder has been used to alter the
  128. // build. See \Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay::buildMultiple().
  129. if (isset($build['_layout_builder']) && !Element::isEmpty($build['_layout_builder'])) {
  130. /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
  131. $field_manager = \Drupal::service('entity_field.manager');
  132. $extra_fields = $field_manager->getExtraFields($entity->getEntityTypeId(), $entity->bundle());
  133. if (!empty($extra_fields['display'])) {
  134. foreach ($extra_fields['display'] as $field_name => $extra_field) {
  135. // If the extra field is not set replace with an empty array to avoid
  136. // the placeholder text from being rendered.
  137. $replacement = isset($build[$field_name]) ? $build[$field_name] : [];
  138. ExtraFieldBlock::replaceFieldPlaceholder($build, $replacement, $field_name);
  139. // After the rendered field in $build has been copied over to the
  140. // ExtraFieldBlock block we must remove it from its original location or
  141. // else it will be rendered twice.
  142. unset($build[$field_name]);
  143. }
  144. }
  145. }
  146. $route_name = \Drupal::routeMatch()->getRouteName();
  147. // If the entity is displayed within a Layout Builder block and the current
  148. // route is in the Layout Builder UI, then remove all contextual link
  149. // placeholders.
  150. if ($display instanceof LayoutBuilderEntityViewDisplay && strpos($route_name, 'layout_builder.') === 0) {
  151. unset($build['#contextual_links']);
  152. }
  153. if (\Drupal::moduleHandler()->moduleExists('quickedit')) {
  154. /** @var \Drupal\layout_builder\QuickEditIntegration $quick_edit_integration */
  155. $quick_edit_integration = \Drupal::classResolver(QuickEditIntegration::class);
  156. $quick_edit_integration->entityViewAlter($build, $entity, $display);
  157. }
  158. }
  159. /**
  160. * Implements hook_entity_build_defaults_alter().
  161. */
  162. function layout_builder_entity_build_defaults_alter(array &$build, EntityInterface $entity, $view_mode) {
  163. // Contextual links are removed for entities viewed in Layout Builder's UI.
  164. // The route.name.is_layout_builder_ui cache context accounts for this
  165. // difference.
  166. // @see layout_builder_entity_view_alter()
  167. // @see \Drupal\layout_builder\Cache\LayoutBuilderUiCacheContext
  168. $build['#cache']['contexts'][] = 'route.name.is_layout_builder_ui';
  169. }
  170. /**
  171. * Implements hook_module_implements_alter().
  172. */
  173. function layout_builder_module_implements_alter(&$implementations, $hook) {
  174. if ($hook === 'entity_view_alter') {
  175. // Ensure that this module's implementation of hook_entity_view_alter() runs
  176. // last so that other modules that use this hook to render extra fields will
  177. // run before it.
  178. $group = $implementations['layout_builder'];
  179. unset($implementations['layout_builder']);
  180. $implementations['layout_builder'] = $group;
  181. }
  182. }
  183. /**
  184. * Implements hook_entity_presave().
  185. */
  186. function layout_builder_entity_presave(EntityInterface $entity) {
  187. if (\Drupal::moduleHandler()->moduleExists('block_content')) {
  188. /** @var \Drupal\layout_builder\InlineBlockEntityOperations $entity_operations */
  189. $entity_operations = \Drupal::classResolver(InlineBlockEntityOperations::class);
  190. $entity_operations->handlePreSave($entity);
  191. }
  192. }
  193. /**
  194. * Implements hook_entity_delete().
  195. */
  196. function layout_builder_entity_delete(EntityInterface $entity) {
  197. if (\Drupal::moduleHandler()->moduleExists('block_content')) {
  198. /** @var \Drupal\layout_builder\InlineBlockEntityOperations $entity_operations */
  199. $entity_operations = \Drupal::classResolver(InlineBlockEntityOperations::class);
  200. $entity_operations->handleEntityDelete($entity);
  201. }
  202. }
  203. /**
  204. * Implements hook_cron().
  205. */
  206. function layout_builder_cron() {
  207. if (\Drupal::moduleHandler()->moduleExists('block_content')) {
  208. /** @var \Drupal\layout_builder\InlineBlockEntityOperations $entity_operations */
  209. $entity_operations = \Drupal::classResolver(InlineBlockEntityOperations::class);
  210. $entity_operations->removeUnused();
  211. }
  212. }
  213. /**
  214. * Implements hook_plugin_filter_TYPE__CONSUMER_alter().
  215. */
  216. function layout_builder_plugin_filter_block__layout_builder_alter(array &$definitions, array $extra) {
  217. // @todo Restore the page title block in https://www.drupal.org/node/2938129.
  218. unset($definitions['page_title_block']);
  219. }
  220. /**
  221. * Implements hook_plugin_filter_TYPE_alter().
  222. */
  223. function layout_builder_plugin_filter_block_alter(array &$definitions, array $extra, $consumer) {
  224. // @todo Determine the 'inline_block' blocks should be allowed outside
  225. // of layout_builder https://www.drupal.org/node/2979142.
  226. if ($consumer !== 'layout_builder' || !isset($extra['list']) || $extra['list'] !== 'inline_blocks') {
  227. foreach ($definitions as $id => $definition) {
  228. if ($definition['id'] === 'inline_block') {
  229. unset($definitions[$id]);
  230. }
  231. }
  232. }
  233. }
  234. /**
  235. * Implements hook_ENTITY_TYPE_access().
  236. */
  237. function layout_builder_block_content_access(EntityInterface $entity, $operation, AccountInterface $account) {
  238. /** @var \Drupal\block_content\BlockContentInterface $entity */
  239. if ($operation === 'view' || $entity->isReusable() || empty(\Drupal::service('inline_block.usage')->getUsage($entity->id()))) {
  240. // If the operation is 'view' or this is reusable block or if this is
  241. // non-reusable that isn't used by this module then don't alter the access.
  242. return AccessResult::neutral();
  243. }
  244. if ($account->hasPermission('create and edit custom blocks')) {
  245. return AccessResult::allowed();
  246. }
  247. return AccessResult::forbidden();
  248. }
  249. /**
  250. * Implements hook_plugin_filter_TYPE__CONSUMER_alter().
  251. */
  252. function layout_builder_plugin_filter_block__block_ui_alter(array &$definitions, array $extra) {
  253. foreach ($definitions as $id => $definition) {
  254. // Filter out any layout_builder-provided block that has required context
  255. // definitions.
  256. if ($definition['provider'] === 'layout_builder' && !empty($definition['context_definitions'])) {
  257. /** @var \Drupal\Core\Plugin\Context\ContextDefinitionInterface $context_definition */
  258. foreach ($definition['context_definitions'] as $context_definition) {
  259. if ($context_definition->isRequired()) {
  260. unset($definitions[$id]);
  261. break;
  262. }
  263. }
  264. }
  265. }
  266. }
  267. /**
  268. * Implements hook_plugin_filter_TYPE__CONSUMER_alter().
  269. */
  270. function layout_builder_plugin_filter_layout__layout_builder_alter(array &$definitions, array $extra) {
  271. // Remove layouts provide by layout discovery that are not needed because of
  272. // layouts provided by this module.
  273. $duplicate_layouts = [
  274. 'layout_twocol',
  275. 'layout_twocol_bricks',
  276. 'layout_threecol_25_50_25',
  277. 'layout_threecol_33_34_33',
  278. ];
  279. foreach ($duplicate_layouts as $duplicate_layout) {
  280. /** @var \Drupal\Core\Layout\LayoutDefinition[] $definitions */
  281. if (isset($definitions[$duplicate_layout])) {
  282. if ($definitions[$duplicate_layout]->getProvider() === 'layout_discovery') {
  283. unset($definitions[$duplicate_layout]);
  284. }
  285. }
  286. }
  287. // Move the one column layout to the top.
  288. if (isset($definitions['layout_onecol']) && $definitions['layout_onecol']->getProvider() === 'layout_discovery') {
  289. $one_col = $definitions['layout_onecol'];
  290. unset($definitions['layout_onecol']);
  291. $definitions = [
  292. 'layout_onecol' => $one_col,
  293. ] + $definitions;
  294. }
  295. }
  296. /**
  297. * Implements hook_plugin_filter_TYPE_alter().
  298. */
  299. function layout_builder_plugin_filter_layout_alter(array &$definitions, array $extra, $consumer) {
  300. // Hide the blank layout plugin from listings.
  301. unset($definitions['layout_builder_blank']);
  302. }
  303. /**
  304. * Implements hook_system_breadcrumb_alter().
  305. */
  306. function layout_builder_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  307. // Remove the extra 'Manage display' breadcrumb for Layout Builder defaults.
  308. if ($route_match->getRouteObject()->hasOption('_layout_builder') && $route_match->getParameter('section_storage_type') === 'defaults') {
  309. $links = array_filter($breadcrumb->getLinks(), function (Link $link) use ($route_match) {
  310. $entity_type_id = $route_match->getParameter('entity_type_id');
  311. return $link->getUrl()->getRouteName() !== "entity.entity_view_display.$entity_type_id.default";
  312. });
  313. // Links cannot be removed from an existing breadcrumb object. Create a new
  314. // object but carry over the cacheable metadata.
  315. $cacheability = CacheableMetadata::createFromObject($breadcrumb);
  316. $breadcrumb = new Breadcrumb();
  317. $breadcrumb->setLinks($links);
  318. $breadcrumb->addCacheableDependency($cacheability);
  319. }
  320. }
  321. /**
  322. * Implements hook_quickedit_render_field().
  323. */
  324. function layout_builder_quickedit_render_field(EntityInterface $entity, $field_name, $view_mode_id, $langcode) {
  325. /** @var \Drupal\layout_builder\QuickEditIntegration $quick_edit_integration */
  326. $quick_edit_integration = \Drupal::classResolver(QuickEditIntegration::class);
  327. return $quick_edit_integration->quickEditRenderField($entity, $field_name, $view_mode_id, $langcode);
  328. }
  329. /**
  330. * Implements hook_entity_translation_create().
  331. */
  332. function layout_builder_entity_translation_create(EntityInterface $translation) {
  333. /** @var \Drupal\Core\Entity\FieldableEntityInterface $translation */
  334. if ($translation->hasField(OverridesSectionStorage::FIELD_NAME) && $translation->getFieldDefinition(OverridesSectionStorage::FIELD_NAME)->isTranslatable()) {
  335. // When creating a new translation do not copy untranslated sections because
  336. // per-language layouts are not supported.
  337. $translation->set(OverridesSectionStorage::FIELD_NAME, []);
  338. }
  339. }
  340. /**
  341. * Implements hook_theme_registry_alter().
  342. */
  343. function layout_builder_theme_registry_alter(&$theme_registry) {
  344. // Move our preprocess to run after
  345. // content_translation_preprocess_language_content_settings_table().
  346. if (!empty($theme_registry['language_content_settings_table']['preprocess functions'])) {
  347. $preprocess_functions = &$theme_registry['language_content_settings_table']['preprocess functions'];
  348. $index = array_search('layout_builder_preprocess_language_content_settings_table', $preprocess_functions);
  349. if ($index !== FALSE) {
  350. unset($preprocess_functions[$index]);
  351. $preprocess_functions[] = 'layout_builder_preprocess_language_content_settings_table';
  352. }
  353. }
  354. }
  355. /**
  356. * Implements hook_preprocess_HOOK() for language-content-settings-table.html.twig.
  357. */
  358. function layout_builder_preprocess_language_content_settings_table(&$variables) {
  359. foreach ($variables['build']['#rows'] as &$row) {
  360. if (isset($row['#field_name']) && $row['#field_name'] === OverridesSectionStorage::FIELD_NAME) {
  361. // Rebuild the label to include a warning about using translations with
  362. // layouts.
  363. $row['data'][1]['data']['field'] = [
  364. 'label' => $row['data'][1]['data']['field'],
  365. 'description' => [
  366. '#type' => 'container',
  367. '#markup' => t('<strong>Warning</strong>: Layout Builder does not support translating layouts. (<a href="https://www.drupal.org/docs/8/core/modules/layout-builder/layout-builder-and-content-translation">online documentation</a>)'),
  368. '#attributes' => [
  369. 'class' => ['layout-builder-translation-warning'],
  370. ],
  371. ],
  372. ];
  373. }
  374. }
  375. }
  376. /**
  377. * Implements hook_theme_suggestions_HOOK_alter().
  378. */
  379. function layout_builder_theme_suggestions_field_alter(&$suggestions, array $variables) {
  380. $element = $variables['element'];
  381. if (isset($element['#third_party_settings']['layout_builder']['view_mode'])) {
  382. // See system_theme_suggestions_field().
  383. $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle'] . '__' . $element['#third_party_settings']['layout_builder']['view_mode'];
  384. }
  385. return $suggestions;
  386. }