bb8ed11797cf04f4314f36d1d7868a4eb193677a
[yaffs-website] / web / core / modules / layout_builder / src / Plugin / Block / FieldBlock.php
1 <?php
2
3 namespace Drupal\layout_builder\Plugin\Block;
4
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;
25
26 /**
27  * Provides a block that renders a field from an entity.
28  *
29  * @Block(
30  *   id = "field_block",
31  *   deriver = "\Drupal\layout_builder\Plugin\Derivative\FieldBlockDeriver",
32  * )
33  */
34 class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
35
36   /**
37    * The entity field manager.
38    *
39    * @var \Drupal\Core\Entity\EntityFieldManagerInterface
40    */
41   protected $entityFieldManager;
42
43   /**
44    * The formatter manager.
45    *
46    * @var \Drupal\Core\Field\FormatterPluginManager
47    */
48   protected $formatterManager;
49
50   /**
51    * The entity type ID.
52    *
53    * @var string
54    */
55   protected $entityTypeId;
56
57   /**
58    * The bundle ID.
59    *
60    * @var string
61    */
62   protected $bundle;
63
64   /**
65    * The field name.
66    *
67    * @var string
68    */
69   protected $fieldName;
70
71   /**
72    * The field definition.
73    *
74    * @var \Drupal\Core\Field\FieldDefinitionInterface
75    */
76   protected $fieldDefinition;
77
78   /**
79    * The module handler.
80    *
81    * @var \Drupal\Core\Extension\ModuleHandlerInterface
82    */
83   protected $moduleHandler;
84
85   /**
86    * The logger.
87    *
88    * @var \Psr\Log\LoggerInterface
89    */
90   protected $logger;
91
92   /**
93    * Constructs a new FieldBlock.
94    *
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
108    *   The logger.
109    */
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;
115
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;
121
122     parent::__construct($configuration, $plugin_id, $plugin_definition);
123   }
124
125   /**
126    * {@inheritdoc}
127    */
128   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
129     return new static(
130       $configuration,
131       $plugin_id,
132       $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')
137     );
138   }
139
140   /**
141    * Gets the entity that has the field.
142    *
143    * @return \Drupal\Core\Entity\FieldableEntityInterface
144    *   The entity.
145    */
146   protected function getEntity() {
147     return $this->getContextValue('entity');
148   }
149
150   /**
151    * {@inheritdoc}
152    */
153   public function build() {
154     $display_settings = $this->getConfiguration()['formatter'];
155     $entity = $this->getEntity();
156     try {
157       $build = $entity->get($this->fieldName)->view($display_settings);
158     }
159     catch (\Exception $e) {
160       $build = [];
161       $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]);
162     }
163     if (!empty($entity->in_preview) && !Element::getVisibleChildren($build)) {
164       $build['content']['#markup'] = new TranslatableMarkup('Placeholder for the "@field" field', ['@field' => $this->getFieldDefinition()->getLabel()]);
165     }
166     CacheableMetadata::createFromObject($this)->applyTo($build);
167     return $build;
168   }
169
170   /**
171    * {@inheritdoc}
172    */
173   protected function blockAccess(AccountInterface $account) {
174     $entity = $this->getEntity();
175
176     // First consult the entity.
177     $access = $entity->access('view', $account, TRUE);
178     if (!$access->isAllowed()) {
179       return $access;
180     }
181
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());
185     }
186
187     // Check field access.
188     $field = $entity->get($this->fieldName);
189     $access = $access->andIf($field->access('view', $account, TRUE));
190     if (!$access->isAllowed()) {
191       return $access;
192     }
193
194     // Check to see if the field has any values.
195     if ($field->isEmpty()) {
196       return $access->andIf(AccessResult::forbidden());
197     }
198     return $access;
199   }
200
201   /**
202    * {@inheritdoc}
203    */
204   public function defaultConfiguration() {
205     return [
206       'label_display' => FALSE,
207       'formatter' => [
208         'label' => 'above',
209         'type' => $this->pluginDefinition['default_formatter'],
210         'settings' => [],
211         'third_party_settings' => [],
212       ],
213     ];
214   }
215
216   /**
217    * {@inheritdoc}
218    */
219   public function blockForm($form, FormStateInterface $form_state) {
220     $config = $this->getConfiguration();
221
222     $form['formatter'] = [
223       '#tree' => TRUE,
224       '#process' => [
225         [$this, 'formatterSettingsProcessCallback'],
226       ],
227     ];
228     $form['formatter']['label'] = [
229       '#type' => 'select',
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.
234       '#options' => [
235         'above' => $this->t('Above'),
236         'inline' => $this->t('Inline'),
237         'hidden' => '- ' . $this->t('Hidden') . ' -',
238         'visually_hidden' => '- ' . $this->t('Visually Hidden') . ' -',
239       ],
240       '#default_value' => $config['formatter']['label'],
241     ];
242
243     $form['formatter']['type'] = [
244       '#type' => 'select',
245       '#title' => $this->t('Formatter'),
246       '#options' => $this->getApplicablePluginOptions($this->getFieldDefinition()),
247       '#required' => TRUE,
248       '#default_value' => $config['formatter']['type'],
249       '#ajax' => [
250         'callback' => [static::class, 'formatterSettingsAjaxCallback'],
251         'wrapper' => 'formatter-settings-wrapper',
252       ],
253     ];
254
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>',
259     ];
260
261     return $form;
262   }
263
264   /**
265    * Render API callback: builds the formatter settings elements.
266    */
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']);
273
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']);
277     }
278     return $element;
279   }
280
281   /**
282    * Adds the formatter third party settings forms.
283    *
284    * @param \Drupal\Core\Field\FormatterInterface $plugin
285    *   The formatter.
286    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
287    *   The field definition.
288    * @param array $form
289    *   The (entire) configuration form array.
290    * @param \Drupal\Core\Form\FormStateInterface $form_state
291    *   The form state.
292    *
293    * @return array
294    *   The formatter third party settings form.
295    */
296   protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
297     $settings_form = [];
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', [
302         $plugin,
303         $field_definition,
304         EntityDisplayBase::CUSTOM_MODE,
305         $form,
306         $form_state,
307       ]);
308     }
309     return $settings_form;
310   }
311
312   /**
313    * Render API callback: gets the layout settings elements.
314    */
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']));
318   }
319
320   /**
321    * {@inheritdoc}
322    */
323   public function blockSubmit($form, FormStateInterface $form_state) {
324     $this->configuration['formatter'] = $form_state->getValue('formatter');
325   }
326
327   /**
328    * Gets the field definition.
329    *
330    * @return \Drupal\Core\Field\FieldDefinitionInterface
331    *   The field definition.
332    */
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];
337     }
338     return $this->fieldDefinition;
339   }
340
341   /**
342    * Returns an array of applicable formatter options for a field.
343    *
344    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
345    *   The field definition.
346    *
347    * @return array
348    *   An array of applicable formatter options.
349    *
350    * @see \Drupal\field_ui\Form\EntityDisplayFormBase::getApplicablePluginOptions()
351    */
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;
359       }
360     }
361     return $applicable_options;
362   }
363
364   /**
365    * Gets the formatter object.
366    *
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.
371    *
372    * @return \Drupal\Core\Field\FormatterInterface
373    *   The formatter object.
374    */
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'];
384       }
385     }
386
387     return $this->formatterManager->getInstance([
388       'configuration' => $configuration,
389       'field_definition' => $this->getFieldDefinition(),
390       'view_mode' => EntityDisplayBase::CUSTOM_MODE,
391       'prepare' => TRUE,
392     ]);
393   }
394
395 }