3 namespace Drupal\layout_builder\Plugin\Block;
5 use Drupal\Component\Plugin\Factory\DefaultFactory;
6 use Drupal\Component\Utility\NestedArray;
7 use Drupal\Core\Access\AccessResult;
8 use Drupal\Core\Block\BlockBase;
9 use Drupal\Core\Cache\CacheableMetadata;
10 use Drupal\Core\Entity\EntityDisplayBase;
11 use Drupal\Core\Entity\EntityFieldManagerInterface;
12 use Drupal\Core\Entity\FieldableEntityInterface;
13 use Drupal\Core\Extension\ModuleHandlerInterface;
14 use Drupal\Core\Field\FieldDefinitionInterface;
15 use Drupal\Core\Field\FormatterInterface;
16 use Drupal\Core\Field\FormatterPluginManager;
17 use Drupal\Core\Form\FormStateInterface;
18 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
19 use Drupal\Core\Plugin\ContextAwarePluginInterface;
20 use Drupal\Core\Render\Element;
21 use Drupal\Core\Session\AccountInterface;
22 use Drupal\Core\StringTranslation\TranslatableMarkup;
23 use Psr\Log\LoggerInterface;
24 use Symfony\Component\DependencyInjection\ContainerInterface;
27 * Provides a block that renders a field from an entity.
31 * deriver = "\Drupal\layout_builder\Plugin\Derivative\FieldBlockDeriver",
34 class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
37 * The entity field manager.
39 * @var \Drupal\Core\Entity\EntityFieldManagerInterface
41 protected $entityFieldManager;
44 * The formatter manager.
46 * @var \Drupal\Core\Field\FormatterPluginManager
48 protected $formatterManager;
55 protected $entityTypeId;
72 * The field definition.
74 * @var \Drupal\Core\Field\FieldDefinitionInterface
76 protected $fieldDefinition;
81 * @var \Drupal\Core\Extension\ModuleHandlerInterface
83 protected $moduleHandler;
88 * @var \Psr\Log\LoggerInterface
93 * Constructs a new FieldBlock.
95 * @param array $configuration
96 * A configuration array containing information about the plugin instance.
97 * @param string $plugin_id
98 * The plugin ID for the plugin instance.
99 * @param mixed $plugin_definition
100 * The plugin implementation definition.
101 * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
102 * The entity field manager.
103 * @param \Drupal\Core\Field\FormatterPluginManager $formatter_manager
104 * The formatter manager.
105 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
106 * The module handler.
107 * @param \Psr\Log\LoggerInterface $logger
110 public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFieldManagerInterface $entity_field_manager, FormatterPluginManager $formatter_manager, ModuleHandlerInterface $module_handler, LoggerInterface $logger) {
111 $this->entityFieldManager = $entity_field_manager;
112 $this->formatterManager = $formatter_manager;
113 $this->moduleHandler = $module_handler;
114 $this->logger = $logger;
116 // Get the entity type and field name from the plugin ID.
117 list (, $entity_type_id, $bundle, $field_name) = explode(static::DERIVATIVE_SEPARATOR, $plugin_id, 4);
118 $this->entityTypeId = $entity_type_id;
119 $this->bundle = $bundle;
120 $this->fieldName = $field_name;
122 parent::__construct($configuration, $plugin_id, $plugin_definition);
128 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
133 $container->get('entity_field.manager'),
134 $container->get('plugin.manager.field.formatter'),
135 $container->get('module_handler'),
136 $container->get('logger.channel.layout_builder')
141 * Gets the entity that has the field.
143 * @return \Drupal\Core\Entity\FieldableEntityInterface
146 protected function getEntity() {
147 return $this->getContextValue('entity');
153 public function build() {
154 $display_settings = $this->getConfiguration()['formatter'];
155 $entity = $this->getEntity();
157 $build = $entity->get($this->fieldName)->view($display_settings);
159 catch (\Exception $e) {
161 $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]);
163 if (!empty($entity->in_preview) && !Element::getVisibleChildren($build)) {
164 $build['content']['#markup'] = new TranslatableMarkup('Placeholder for the "@field" field', ['@field' => $this->getFieldDefinition()->getLabel()]);
166 CacheableMetadata::createFromObject($this)->applyTo($build);
173 protected function blockAccess(AccountInterface $account) {
174 $entity = $this->getEntity();
176 // First consult the entity.
177 $access = $entity->access('view', $account, TRUE);
178 if (!$access->isAllowed()) {
182 // Check that the entity in question has this field.
183 if (!$entity instanceof FieldableEntityInterface || !$entity->hasField($this->fieldName)) {
184 return $access->andIf(AccessResult::forbidden());
187 // Check field access.
188 $field = $entity->get($this->fieldName);
189 $access = $access->andIf($field->access('view', $account, TRUE));
190 if (!$access->isAllowed()) {
194 // Check to see if the field has any values.
195 if ($field->isEmpty()) {
196 return $access->andIf(AccessResult::forbidden());
204 public function defaultConfiguration() {
206 'label_display' => FALSE,
209 'type' => $this->pluginDefinition['default_formatter'],
211 'third_party_settings' => [],
219 public function blockForm($form, FormStateInterface $form_state) {
220 $config = $this->getConfiguration();
222 $form['formatter'] = [
225 [$this, 'formatterSettingsProcessCallback'],
228 $form['formatter']['label'] = [
230 '#title' => $this->t('Label'),
231 // @todo This is directly copied from
232 // \Drupal\field_ui\Form\EntityViewDisplayEditForm::getFieldLabelOptions(),
233 // resolve this in https://www.drupal.org/project/drupal/issues/2933924.
235 'above' => $this->t('Above'),
236 'inline' => $this->t('Inline'),
237 'hidden' => '- ' . $this->t('Hidden') . ' -',
238 'visually_hidden' => '- ' . $this->t('Visually Hidden') . ' -',
240 '#default_value' => $config['formatter']['label'],
243 $form['formatter']['type'] = [
245 '#title' => $this->t('Formatter'),
246 '#options' => $this->getApplicablePluginOptions($this->getFieldDefinition()),
248 '#default_value' => $config['formatter']['type'],
250 'callback' => [static::class, 'formatterSettingsAjaxCallback'],
251 'wrapper' => 'formatter-settings-wrapper',
255 // Add the formatter settings to the form via AJAX.
256 $form['formatter']['settings_wrapper'] = [
257 '#prefix' => '<div id="formatter-settings-wrapper">',
258 '#suffix' => '</div>',
265 * Render API callback: builds the formatter settings elements.
267 public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form) {
268 if ($formatter = $this->getFormatter($element['#parents'], $form_state)) {
269 $element['settings_wrapper']['settings'] = $formatter->settingsForm($complete_form, $form_state);
270 $element['settings_wrapper']['settings']['#parents'] = array_merge($element['#parents'], ['settings']);
271 $element['settings_wrapper']['third_party_settings'] = $this->thirdPartySettingsForm($formatter, $this->getFieldDefinition(), $complete_form, $form_state);
272 $element['settings_wrapper']['third_party_settings']['#parents'] = array_merge($element['#parents'], ['third_party_settings']);
274 // Store the array parents for our element so that we can retrieve the
275 // formatter settings in our AJAX callback.
276 $form_state->set('field_block_array_parents', $element['#array_parents']);
282 * Adds the formatter third party settings forms.
284 * @param \Drupal\Core\Field\FormatterInterface $plugin
286 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
287 * The field definition.
289 * The (entire) configuration form array.
290 * @param \Drupal\Core\Form\FormStateInterface $form_state
294 * The formatter third party settings form.
296 protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
298 // Invoke hook_field_formatter_third_party_settings_form(), keying resulting
299 // subforms by module name.
300 foreach ($this->moduleHandler->getImplementations('field_formatter_third_party_settings_form') as $module) {
301 $settings_form[$module] = $this->moduleHandler->invoke($module, 'field_formatter_third_party_settings_form', [
304 EntityDisplayBase::CUSTOM_MODE,
309 return $settings_form;
313 * Render API callback: gets the layout settings elements.
315 public static function formatterSettingsAjaxCallback(array $form, FormStateInterface $form_state) {
316 $formatter_array_parents = $form_state->get('field_block_array_parents');
317 return NestedArray::getValue($form, array_merge($formatter_array_parents, ['settings_wrapper']));
323 public function blockSubmit($form, FormStateInterface $form_state) {
324 $this->configuration['formatter'] = $form_state->getValue('formatter');
328 * Gets the field definition.
330 * @return \Drupal\Core\Field\FieldDefinitionInterface
331 * The field definition.
333 protected function getFieldDefinition() {
334 if (empty($this->fieldDefinition)) {
335 $field_definitions = $this->entityFieldManager->getFieldDefinitions($this->entityTypeId, $this->bundle);
336 $this->fieldDefinition = $field_definitions[$this->fieldName];
338 return $this->fieldDefinition;
342 * Returns an array of applicable formatter options for a field.
344 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
345 * The field definition.
348 * An array of applicable formatter options.
350 * @see \Drupal\field_ui\Form\EntityDisplayFormBase::getApplicablePluginOptions()
352 protected function getApplicablePluginOptions(FieldDefinitionInterface $field_definition) {
353 $options = $this->formatterManager->getOptions($field_definition->getType());
354 $applicable_options = [];
355 foreach ($options as $option => $label) {
356 $plugin_class = DefaultFactory::getPluginClass($option, $this->formatterManager->getDefinition($option));
357 if ($plugin_class::isApplicable($field_definition)) {
358 $applicable_options[$option] = $label;
361 return $applicable_options;
365 * Gets the formatter object.
367 * @param array $parents
368 * The #parents of the element representing the formatter.
369 * @param \Drupal\Core\Form\FormStateInterface $form_state
370 * The current state of the form.
372 * @return \Drupal\Core\Field\FormatterInterface
373 * The formatter object.
375 protected function getFormatter(array $parents, FormStateInterface $form_state) {
376 // Use the processed values, if available.
377 $configuration = NestedArray::getValue($form_state->getValues(), $parents);
378 if (!$configuration) {
379 // Next check the raw user input.
380 $configuration = NestedArray::getValue($form_state->getUserInput(), $parents);
381 if (!$configuration) {
382 // If no user input exists, use the default values.
383 $configuration = $this->getConfiguration()['formatter'];
387 return $this->formatterManager->getInstance([
388 'configuration' => $configuration,
389 'field_definition' => $this->getFieldDefinition(),
390 'view_mode' => EntityDisplayBase::CUSTOM_MODE,