Commit e14a020d authored by effulgentsia's avatar effulgentsia

Issue #2796173 by tim.plunkett, samuel.mortenson, xjm, jibran, effulgentsia,...

Issue #2796173 by tim.plunkett, samuel.mortenson, xjm, jibran, effulgentsia, dawehner, swentel, tedbow, phenaproxima, larowlan, yoroy, dsnopek, tacituseu, japerry, webchick, amateescu, aspilicious: Add experimental Field Layout module to allow entity view/form modes to switch between layouts
parent b47dc9e2
......@@ -95,6 +95,7 @@
"drupal/editor": "self.version",
"drupal/entity_reference": "self.version",
"drupal/field": "self.version",
"drupal/field_layout": "self.version",
"drupal/field_ui": "self.version",
"drupal/file": "self.version",
"drupal/filter": "self.version",
......
core.entity_view_display.*.*.*.third_party.field_layout:
type: field_layout.third_party_settings
core.entity_form_display.*.*.*.third_party.field_layout:
type: field_layout.third_party_settings
field_layout.third_party_settings:
type: mapping
label: 'Per-view-mode field layout settings'
mapping:
id:
type: string
label: 'Layout ID'
settings:
type: layout_plugin.settings.[%parent.id]
label: 'Layout settings'
name: 'Field Layout'
type: module
description: 'Adds layout capabilities to the Field UI.'
package: Core (Experimental)
version: VERSION
core: 8.x
dependencies:
- layout_discovery
<?php
/**
* @file
* Contains install and update functions for Field Layout.
*/
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\field_layout\Display\EntityDisplayWithLayoutInterface;
/**
* Implements hook_install().
*/
function field_layout_install() {
// Ensure each entity display has a layout.
$entity_save = function (EntityDisplayWithLayoutInterface $entity) {
$entity->ensureLayout()->save();
};
array_map($entity_save, EntityViewDisplay::loadMultiple());
array_map($entity_save, EntityFormDisplay::loadMultiple());
// Invalidate the render cache since all content will now have a layout.
Cache::invalidateTags(['rendered']);
}
/**
* Implements hook_uninstall().
*/
function field_layout_uninstall() {
// Reset each entity display to use the one-column layout to best approximate
// the absence of layouts.
$entity_save = function (EntityDisplayWithLayoutInterface $entity) {
$entity->setLayoutId('layout_onecol')->save();
};
array_map($entity_save, EntityViewDisplay::loadMultiple());
array_map($entity_save, EntityFormDisplay::loadMultiple());
// Invalidate the render cache since all content will no longer have a layout.
Cache::invalidateTags(['rendered']);
}
# @todo Move to layout_discovery in https://www.drupal.org/node/2840832.
layout_onecol:
label: 'One column'
path: layouts/onecol
template: layout--onecol
category: 'Columns: 1'
default_region: content
regions:
content:
label: Content
layout_twocol:
label: 'Two column'
path: layouts/twocol
template: layout--twocol
library: field_layout/drupal.layout.twocol
category: 'Columns: 2'
default_region: left
regions:
left:
label: Left
right:
label: Right
drupal.layout.twocol:
version: VERSION
css:
layout:
layouts/twocol/twocol.layout.css: {}
<?php
/**
* @file
* Provides hook implementations for Field Layout.
*/
use Drupal\Core\Entity\ContentEntityFormInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\field_layout\Display\EntityDisplayWithLayoutInterface;
use Drupal\field_layout\Entity\FieldLayoutEntityFormDisplay;
use Drupal\field_layout\Entity\FieldLayoutEntityViewDisplay;
use Drupal\field_layout\FieldLayoutBuilder;
use Drupal\field_layout\Form\FieldLayoutEntityFormDisplayEditForm;
use Drupal\field_layout\Form\FieldLayoutEntityViewDisplayEditForm;
/**
* Implements hook_help().
*/
function field_layout_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.field_layout':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Field Layout module allows you to arrange fields into regions on forms and displays of entities such as nodes and users.') . '</p>';
$output .= '<p>' . t('For more information, see the <a href=":field-layout-documentation">online documentation for the Field Layout module</a>.', [':field-layout-documentation' => 'https://www.drupal.org/documentation/modules/field_layout']) . '</p>';
return $output;
}
}
/**
* Implements hook_entity_type_alter().
*/
function field_layout_entity_type_alter(array &$entity_types) {
/** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
$entity_types['entity_view_display']->setClass(FieldLayoutEntityViewDisplay::class);
$entity_types['entity_form_display']->setClass(FieldLayoutEntityFormDisplay::class);
// The form classes are only needed when Field UI is installed.
if (\Drupal::moduleHandler()->moduleExists('field_ui')) {
$entity_types['entity_view_display']->setFormClass('edit', FieldLayoutEntityViewDisplayEditForm::class);
$entity_types['entity_form_display']->setFormClass('edit', FieldLayoutEntityFormDisplayEditForm::class);
}
}
/**
* Implements hook_entity_view_alter().
*/
function field_layout_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
if ($display instanceof EntityDisplayWithLayoutInterface) {
\Drupal::classResolver()->getInstanceFromDefinition(FieldLayoutBuilder::class)
->buildView($build, $display);
}
}
/**
* Implements hook_form_alter().
*/
function field_layout_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form_object = $form_state->getFormObject();
if ($form_object instanceof ContentEntityFormInterface && $display = $form_object->getFormDisplay($form_state)) {
if ($display instanceof EntityDisplayWithLayoutInterface) {
\Drupal::classResolver()->getInstanceFromDefinition(FieldLayoutBuilder::class)
->buildForm($form, $display);
}
}
}
{#
/**
* @file
* Default theme implementation to display a one-column layout.
*
* Available variables:
* - content: The content for this layout.
* - attributes: HTML attributes for the layout <div>.
*
* @ingroup themeable
*/
#}
{%
set classes = [
'layout--onecol',
]
%}
{% if content %}
<div{{ attributes.addClass(classes) }}>
<div class="layout-region layout-region--content">
{{ content }}
</div>
</div>
{% endif %}
{#
/**
* @file
* Default theme implementation to display a two-column layout.
*
* Available variables:
* - content: The content for this layout.
* - attributes: HTML attributes for the layout <div>.
*
* @ingroup themeable
*/
#}
{%
set classes = [
'layout--twocol',
]
%}
{% if content %}
<div{{ attributes.addClass(classes) }}>
<div class="layout-region layout-region--left">
{{ content.left }}
</div>
<div class="layout-region layout-region--right">
{{ content.right }}
</div>
</div>
{% endif %}
.layout--twocol {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.layout--twocol > .layout-region {
flex: 0 1 50%;
max-width: 50%;
}
.layout--twocol > .layout-region--left {
max-width: calc(50% - 10px);
margin-right: 10px;
}
<?php
namespace Drupal\field_layout\Display;
use Drupal\Core\Entity\Display\EntityDisplayInterface;
use Drupal\Core\Layout\LayoutInterface;
/**
* Provides a common interface for entity displays that have layout.
*/
interface EntityDisplayWithLayoutInterface extends EntityDisplayInterface {
/**
* Gets the default region.
*
* @return string
* The default region for this display.
*/
public function getDefaultRegion();
/**
* Gets the layout plugin ID for this display.
*
* @return string
* The layout plugin ID.
*/
public function getLayoutId();
/**
* Gets the layout plugin settings for this display.
*
* @return mixed[]
* The layout plugin settings.
*/
public function getLayoutSettings();
/**
* Sets the layout plugin ID for this display.
*
* @param string|null $layout_id
* Either a valid layout plugin ID, or NULL to remove the layout setting.
* @param array $layout_settings
* (optional) An array of settings for this layout.
*
* @return $this
*/
public function setLayoutId($layout_id, array $layout_settings = []);
/**
* Sets the layout plugin for this display.
*
* @param \Drupal\Core\Layout\LayoutInterface $layout
* A layout plugin.
*
* @return $this
*/
public function setLayout(LayoutInterface $layout);
/**
* Gets the layout plugin for this display.
*
* @return \Drupal\Core\Layout\LayoutInterface
* The layout plugin.
*/
public function getLayout();
/**
* Ensures this entity has a layout.
*
* @param string $default_layout_id
* (optional) The layout ID to use as a default. Defaults to
* 'layout_onecol'.
*
* @return $this
*/
public function ensureLayout($default_layout_id = 'layout_onecol');
}
<?php
namespace Drupal\field_layout\Entity;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Layout\LayoutInterface;
/**
* Provides shared code for entity displays.
*
* Both EntityViewDisplay and EntityFormDisplay must maintain their parent
* hierarchy, while being identically enhanced by Field Layout. This trait
* contains the code they both share.
*/
trait FieldLayoutEntityDisplayTrait {
/**
* Gets a layout definition.
*
* @param string $layout_id
* The layout ID.
*
* @return \Drupal\Core\Layout\LayoutDefinition
* The layout definition.
*/
protected function getLayoutDefinition($layout_id) {
return \Drupal::service('plugin.manager.core.layout')->getDefinition($layout_id);
}
/**
* Implements \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface::getLayoutId().
*/
public function getLayoutId() {
return $this->getThirdPartySetting('field_layout', 'id');
}
/**
* Implements \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface::getLayoutSettings().
*/
public function getLayoutSettings() {
return $this->getThirdPartySetting('field_layout', 'settings', []);
}
/**
* Implements \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface::setLayoutId().
*/
public function setLayoutId($layout_id, array $layout_settings = []) {
if ($this->getLayoutId() !== $layout_id) {
// @todo Devise a mechanism for mapping old regions to new ones in
// https://www.drupal.org/node/2796877.
$layout_definition = $this->getLayoutDefinition($layout_id);
$new_region = $layout_definition->getDefaultRegion();
$layout_regions = $layout_definition->getRegions();
foreach ($this->getComponents() as $name => $component) {
if (isset($component['region']) && !isset($layout_regions[$component['region']])) {
$component['region'] = $new_region;
$this->setComponent($name, $component);
}
}
}
$this->setThirdPartySetting('field_layout', 'id', $layout_id);
// Instantiate the plugin and consult it for the updated plugin
// configuration. Once layouts are no longer stored as third party settings,
// this will be handled by the code in
// \Drupal\Core\Config\Entity\ConfigEntityBase::set() that handles
// \Drupal\Core\Entity\EntityWithPluginCollectionInterface.
$layout_settings = $this->doGetLayout($layout_id, $layout_settings)->getConfiguration();
$this->setThirdPartySetting('field_layout', 'settings', $layout_settings);
return $this;
}
/**
* Implements \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface::setLayout().
*/
public function setLayout(LayoutInterface $layout) {
$this->setLayoutId($layout->getPluginId(), $layout->getConfiguration());
return $this;
}
/**
* Implements \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface::getLayout().
*/
public function getLayout() {
return $this->doGetLayout($this->getLayoutId(), $this->getLayoutSettings());
}
/**
* Gets the layout plugin.
*
* @param string $layout_id
* A layout plugin ID.
* @param array $layout_settings
* An array of settings.
*
* @return \Drupal\Core\Layout\LayoutInterface
* The layout plugin.
*/
protected function doGetLayout($layout_id, array $layout_settings) {
return \Drupal::service('plugin.manager.core.layout')->createInstance($layout_id, $layout_settings);
}
/**
* Overrides \Drupal\Core\Entity\EntityDisplayBase::init().
*/
protected function init() {
$this->ensureLayout();
parent::init();
}
/**
* Overrides \Drupal\Core\Entity\EntityDisplayBase::preSave().
*/
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
// Ensure the plugin configuration is updated. Once layouts are no longer
// stored as third party settings, this will be handled by the code in
// \Drupal\Core\Config\Entity\ConfigEntityBase::preSave() that handles
// \Drupal\Core\Entity\EntityWithPluginCollectionInterface.
if ($this->getLayoutId()) {
$this->setLayout($this->getLayout());
}
}
/**
* {@inheritdoc}
*/
public function ensureLayout($default_layout_id = 'layout_onecol') {
if (!$this->getLayoutId()) {
$this->setLayoutId($default_layout_id);
}
return $this;
}
/**
* Overrides \Drupal\Core\Entity\EntityDisplayBase::calculateDependencies().
*
* @see \Drupal\Core\Plugin\PluginDependencyTrait::calculatePluginDependencies()
*
* @todo Remove once https://www.drupal.org/node/2821191 is resolved.
*/
public function calculateDependencies() {
parent::calculateDependencies();
// This can be called during uninstallation, so check for a valid ID first.
if ($this->getLayoutId()) {
/** @var \Drupal\Core\Layout\LayoutInterface $layout */
$layout = $this->getLayout();
$definition = $layout->getPluginDefinition();
if (!in_array($definition->getProvider(), ['core', 'component'])) {
$this->addDependency('module', $definition->getProvider());
}
if ($config_dependencies = $definition->getConfigDependencies()) {
$this->addDependencies($config_dependencies);
}
if ($layout_dependencies = $layout->calculateDependencies()) {
$this->addDependencies($layout_dependencies);
}
}
}
}
<?php
namespace Drupal\field_layout\Entity;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\field_layout\Display\EntityDisplayWithLayoutInterface;
/**
* Provides an entity form display entity that has a layout.
*/
class FieldLayoutEntityFormDisplay extends EntityFormDisplay implements EntityDisplayWithLayoutInterface {
use FieldLayoutEntityDisplayTrait;
/**
* {@inheritdoc}
*/
public function getDefaultRegion() {
// This cannot be provided by the trait due to
// https://bugs.php.net/bug.php?id=71414 which is fixed in PHP 7.0.6.
return $this->getLayoutDefinition($this->getLayoutId())->getDefaultRegion();
}
}
<?php
namespace Drupal\field_layout\Entity;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\field_layout\Display\EntityDisplayWithLayoutInterface;
/**
* Provides an entity view display entity that has a layout.
*/
class FieldLayoutEntityViewDisplay extends EntityViewDisplay implements EntityDisplayWithLayoutInterface {
use FieldLayoutEntityDisplayTrait;
/**
* {@inheritdoc}
*/
public function getDefaultRegion() {
// This cannot be provided by the trait due to
// https://bugs.php.net/bug.php?id=71414 which is fixed in PHP 7.0.6.
return $this->getLayoutDefinition($this->getLayoutId())->getDefaultRegion();
}
}
<?php
namespace Drupal\field_layout;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\field_layout\Display\EntityDisplayWithLayoutInterface;
use Drupal\Core\Layout\LayoutPluginManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Builds a field layout.
*/
class FieldLayoutBuilder implements ContainerInjectionInterface {
/**
* The layout plugin manager.
*
* @var \Drupal\Core\Layout\LayoutPluginManagerInterface
*/
protected $layoutPluginManager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Constructs a new FieldLayoutBuilder.
*
* @param \Drupal\Core\Layout\LayoutPluginManagerInterface $layout_plugin_manager
* The layout plugin manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
public function __construct(LayoutPluginManagerInterface $layout_plugin_manager, EntityFieldManagerInterface $entity_field_manager) {
$this->layoutPluginManager = $layout_plugin_manager;
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.core.layout'),
$container->get('entity_field.manager')
);
}
/**
* Applies the layout to an entity build.
*
* @param array $build
* A renderable array representing the entity content or form.
* @param \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface $display
* The entity display holding the display options configured for the entity
* components.
*/
public function buildView(array &$build, EntityDisplayWithLayoutInterface $display) {
$layout_definition = $this->layoutPluginManager->getDefinition($display->getLayoutId(), FALSE);
if ($layout_definition && $fields = $this->getFields($build, $display, 'view')) {
// Add the regions to the $build in the correct order.
$regions = array_fill_keys($layout_definition->getRegionNames(), []);
foreach ($fields as $name => $field) {
// Move the field from the top-level of $build into a region-specific
// section.
// @todo Ideally the array structure would remain unchanged, see
// https://www.drupal.org/node/2846393.
$regions[$field['region']][$name] = $build[$name];
unset($build[$name]);
}
// Ensure this will not conflict with any existing array elements by
// prefixing with an underscore.
$build['_field_layout'] = $display->getLayout()->build($regions);
}
}
/**
* Applies the layout to an entity form.
*
* @param array $build
* A renderable array representing the entity content or form.
* @param \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface $display
* The entity display holding the display options configured for the entity
* components.
*/
public function buildForm(array &$build, EntityDisplayWithLayoutInterface $display) {
$layout_definition = $this->layoutPluginManager->getDefinition($display->getLayoutId(), FALSE);
if ($layout_definition && $fields = $this->getFields($build, $display, 'form')) {
$fill = [];
$fill['#process'][] = '\Drupal\Core\Render\Element\RenderElement::processGroup';
$fill['#pre_render'][] = '\Drupal\Core\Render\Element\RenderElement::preRenderGroup';
// Add the regions to the $build in the correct order.
$regions = array_fill_keys($layout_definition->getRegionNames(), $fill);
foreach ($fields as $name => $field) {
// As this is a form, #group can be used to relocate the fields. This
// avoids breaking hook_form_alter() implementations by not actually
// moving the field in the form structure. If a #group is already set,
// do not overwrite it.
if (!isset($build[$name]['#group'])) {
$build[$name]['#group'] = $field['region'];
}
}
// Ensure this will not conflict with any existing array elements by
// prefixing with an underscore.
$build['_field_layout'] = $display->getLayout()->build($regions);
}