View source
<?php
namespace Drupal\layout_builder\Plugin\Block;
use Drupal\Component\Plugin\Factory\DefaultFactory;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityDisplayBase;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FormatterInterface;
use Drupal\Core\Field\FormatterPluginManager;
use Drupal\Core\Form\EnforcedResponseException;
use Drupal\Core\Form\FormHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
protected $entityFieldManager;
protected $formatterManager;
protected $entityTypeId;
protected $bundle;
protected $fieldName;
protected $fieldDefinition;
protected $moduleHandler;
protected $logger;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFieldManagerInterface $entity_field_manager, FormatterPluginManager $formatter_manager, ModuleHandlerInterface $module_handler, LoggerInterface $logger) {
$this->entityFieldManager = $entity_field_manager;
$this->formatterManager = $formatter_manager;
$this->moduleHandler = $module_handler;
$this->logger = $logger;
list(, $entity_type_id, $bundle, $field_name) = explode(static::DERIVATIVE_SEPARATOR, $plugin_id, 4);
$this->entityTypeId = $entity_type_id;
$this->bundle = $bundle;
$this->fieldName = $field_name;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_field.manager'), $container
->get('plugin.manager.field.formatter'), $container
->get('module_handler'), $container
->get('logger.channel.layout_builder'));
}
protected function getEntity() {
return $this
->getContextValue('entity');
}
public function build() {
$display_settings = $this
->getConfiguration()['formatter'];
$display_settings['third_party_settings']['layout_builder']['view_mode'] = $this
->getContextValue('view_mode');
$entity = $this
->getEntity();
try {
$build = $entity
->get($this->fieldName)
->view($display_settings);
} catch (EnforcedResponseException $e) {
throw $e;
} catch (\Exception $e) {
$build = [];
$this->logger
->warning('The field "%field" failed to render with the error of "%error".', [
'%field' => $this->fieldName,
'%error' => $e
->getMessage(),
]);
}
CacheableMetadata::createFromRenderArray($build)
->addCacheableDependency($this)
->applyTo($build);
return $build;
}
public function getPreviewFallbackString() {
return new TranslatableMarkup('"@field" field', [
'@field' => $this
->getFieldDefinition()
->getLabel(),
]);
}
protected function blockAccess(AccountInterface $account) {
$entity = $this
->getEntity();
$access = $entity
->access('view', $account, TRUE);
if (!$access
->isAllowed()) {
return $access;
}
if (!$entity instanceof FieldableEntityInterface || !$entity
->hasField($this->fieldName)) {
return $access
->andIf(AccessResult::forbidden());
}
$field = $entity
->get($this->fieldName);
$access = $access
->andIf($field
->access('view', $account, TRUE));
if (!$access
->isAllowed()) {
return $access;
}
if ($field
->isEmpty()) {
return $access
->andIf(AccessResult::forbidden());
}
return $access;
}
public function defaultConfiguration() {
return [
'label_display' => FALSE,
'formatter' => [
'label' => 'above',
'type' => $this->pluginDefinition['default_formatter'],
'settings' => [],
'third_party_settings' => [],
],
];
}
public function blockForm($form, FormStateInterface $form_state) {
$config = $this
->getConfiguration();
$form['formatter'] = [
'#tree' => TRUE,
'#process' => [
[
$this,
'formatterSettingsProcessCallback',
],
],
];
$form['formatter']['label'] = [
'#type' => 'select',
'#title' => $this
->t('Label'),
'#options' => [
'above' => $this
->t('Above'),
'inline' => $this
->t('Inline'),
'hidden' => '- ' . $this
->t('Hidden') . ' -',
'visually_hidden' => '- ' . $this
->t('Visually Hidden') . ' -',
],
'#default_value' => $config['formatter']['label'],
];
$form['formatter']['type'] = [
'#type' => 'select',
'#title' => $this
->t('Formatter'),
'#options' => $this
->getApplicablePluginOptions($this
->getFieldDefinition()),
'#required' => TRUE,
'#default_value' => $config['formatter']['type'],
'#ajax' => [
'callback' => [
static::class,
'formatterSettingsAjaxCallback',
],
'wrapper' => 'formatter-settings-wrapper',
],
];
$form['formatter']['settings_wrapper'] = [
'#prefix' => '<div id="formatter-settings-wrapper">',
'#suffix' => '</div>',
];
return $form;
}
public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form) {
if ($formatter = $this
->getFormatter($element['#parents'], $form_state)) {
$element['settings_wrapper']['settings'] = $formatter
->settingsForm($complete_form, $form_state);
$element['settings_wrapper']['settings']['#parents'] = array_merge($element['#parents'], [
'settings',
]);
$element['settings_wrapper']['third_party_settings'] = $this
->thirdPartySettingsForm($formatter, $this
->getFieldDefinition(), $complete_form, $form_state);
$element['settings_wrapper']['third_party_settings']['#parents'] = array_merge($element['#parents'], [
'third_party_settings',
]);
FormHelper::rewriteStatesSelector($element['settings_wrapper'], "fields[{$this->fieldName}][settings_edit_form]", 'settings[formatter]');
$form_state
->set('field_block_array_parents', $element['#array_parents']);
}
return $element;
}
protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
$settings_form = [];
foreach ($this->moduleHandler
->getImplementations('field_formatter_third_party_settings_form') as $module) {
$settings_form[$module] = $this->moduleHandler
->invoke($module, 'field_formatter_third_party_settings_form', [
$plugin,
$field_definition,
EntityDisplayBase::CUSTOM_MODE,
$form,
$form_state,
]);
}
return $settings_form;
}
public static function formatterSettingsAjaxCallback(array $form, FormStateInterface $form_state) {
$formatter_array_parents = $form_state
->get('field_block_array_parents');
return NestedArray::getValue($form, array_merge($formatter_array_parents, [
'settings_wrapper',
]));
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['formatter'] = $form_state
->getValue('formatter');
}
protected function getFieldDefinition() {
if (empty($this->fieldDefinition)) {
$field_definitions = $this->entityFieldManager
->getFieldDefinitions($this->entityTypeId, $this->bundle);
$this->fieldDefinition = $field_definitions[$this->fieldName];
}
return $this->fieldDefinition;
}
protected function getApplicablePluginOptions(FieldDefinitionInterface $field_definition) {
$options = $this->formatterManager
->getOptions($field_definition
->getType());
$applicable_options = [];
foreach ($options as $option => $label) {
$plugin_class = DefaultFactory::getPluginClass($option, $this->formatterManager
->getDefinition($option));
if ($plugin_class::isApplicable($field_definition)) {
$applicable_options[$option] = $label;
}
}
return $applicable_options;
}
protected function getFormatter(array $parents, FormStateInterface $form_state) {
$configuration = NestedArray::getValue($form_state
->getValues(), $parents);
if (!$configuration) {
$configuration = NestedArray::getValue($form_state
->getUserInput(), $parents);
if (!$configuration) {
$configuration = $this
->getConfiguration()['formatter'];
}
}
return $this->formatterManager
->getInstance([
'configuration' => $configuration,
'field_definition' => $this
->getFieldDefinition(),
'view_mode' => EntityDisplayBase::CUSTOM_MODE,
'prepare' => TRUE,
]);
}
}