Pull merge.
[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\Session\AccountInterface;
21 use Drupal\Core\StringTranslation\TranslatableMarkup;
22 use Psr\Log\LoggerInterface;
23 use Symfony\Component\DependencyInjection\ContainerInterface;
24
25 /**
26  * Provides a block that renders a field from an entity.
27  *
28  * @Block(
29  *   id = "field_block",
30  *   deriver = "\Drupal\layout_builder\Plugin\Derivative\FieldBlockDeriver",
31  * )
32  */
33 class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
34
35   /**
36    * The entity field manager.
37    *
38    * @var \Drupal\Core\Entity\EntityFieldManagerInterface
39    */
40   protected $entityFieldManager;
41
42   /**
43    * The formatter manager.
44    *
45    * @var \Drupal\Core\Field\FormatterPluginManager
46    */
47   protected $formatterManager;
48
49   /**
50    * The entity type ID.
51    *
52    * @var string
53    */
54   protected $entityTypeId;
55
56   /**
57    * The bundle ID.
58    *
59    * @var string
60    */
61   protected $bundle;
62
63   /**
64    * The field name.
65    *
66    * @var string
67    */
68   protected $fieldName;
69
70   /**
71    * The field definition.
72    *
73    * @var \Drupal\Core\Field\FieldDefinitionInterface
74    */
75   protected $fieldDefinition;
76
77   /**
78    * The module handler.
79    *
80    * @var \Drupal\Core\Extension\ModuleHandlerInterface
81    */
82   protected $moduleHandler;
83
84   /**
85    * The logger.
86    *
87    * @var \Psr\Log\LoggerInterface
88    */
89   protected $logger;
90
91   /**
92    * Constructs a new FieldBlock.
93    *
94    * @param array $configuration
95    *   A configuration array containing information about the plugin instance.
96    * @param string $plugin_id
97    *   The plugin ID for the plugin instance.
98    * @param mixed $plugin_definition
99    *   The plugin implementation definition.
100    * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
101    *   The entity field manager.
102    * @param \Drupal\Core\Field\FormatterPluginManager $formatter_manager
103    *   The formatter manager.
104    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
105    *   The module handler.
106    * @param \Psr\Log\LoggerInterface $logger
107    *   The logger.
108    */
109   public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFieldManagerInterface $entity_field_manager, FormatterPluginManager $formatter_manager, ModuleHandlerInterface $module_handler, LoggerInterface $logger) {
110     $this->entityFieldManager = $entity_field_manager;
111     $this->formatterManager = $formatter_manager;
112     $this->moduleHandler = $module_handler;
113     $this->logger = $logger;
114
115     // Get the entity type and field name from the plugin ID.
116     list (, $entity_type_id, $bundle, $field_name) = explode(static::DERIVATIVE_SEPARATOR, $plugin_id, 4);
117     $this->entityTypeId = $entity_type_id;
118     $this->bundle = $bundle;
119     $this->fieldName = $field_name;
120
121     parent::__construct($configuration, $plugin_id, $plugin_definition);
122   }
123
124   /**
125    * {@inheritdoc}
126    */
127   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
128     return new static(
129       $configuration,
130       $plugin_id,
131       $plugin_definition,
132       $container->get('entity_field.manager'),
133       $container->get('plugin.manager.field.formatter'),
134       $container->get('module_handler'),
135       $container->get('logger.channel.layout_builder')
136     );
137   }
138
139   /**
140    * Gets the entity that has the field.
141    *
142    * @return \Drupal\Core\Entity\FieldableEntityInterface
143    *   The entity.
144    */
145   protected function getEntity() {
146     return $this->getContextValue('entity');
147   }
148
149   /**
150    * {@inheritdoc}
151    */
152   public function build() {
153     $display_settings = $this->getConfiguration()['formatter'];
154     $entity = $this->getEntity();
155     try {
156       $build = $entity->get($this->fieldName)->view($display_settings);
157     }
158     catch (\Exception $e) {
159       $build = [];
160       $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]);
161     }
162     CacheableMetadata::createFromObject($this)->applyTo($build);
163     return $build;
164   }
165
166   /**
167    * {@inheritdoc}
168    */
169   public function getPreviewFallbackString() {
170     return new TranslatableMarkup('Placeholder for the "@field" field', ['@field' => $this->getFieldDefinition()->getLabel()]);
171   }
172
173   /**
174    * {@inheritdoc}
175    */
176   protected function blockAccess(AccountInterface $account) {
177     $entity = $this->getEntity();
178
179     // First consult the entity.
180     $access = $entity->access('view', $account, TRUE);
181     if (!$access->isAllowed()) {
182       return $access;
183     }
184
185     // Check that the entity in question has this field.
186     if (!$entity instanceof FieldableEntityInterface || !$entity->hasField($this->fieldName)) {
187       return $access->andIf(AccessResult::forbidden());
188     }
189
190     // Check field access.
191     $field = $entity->get($this->fieldName);
192     $access = $access->andIf($field->access('view', $account, TRUE));
193     if (!$access->isAllowed()) {
194       return $access;
195     }
196
197     // Check to see if the field has any values.
198     if ($field->isEmpty()) {
199       return $access->andIf(AccessResult::forbidden());
200     }
201     return $access;
202   }
203
204   /**
205    * {@inheritdoc}
206    */
207   public function defaultConfiguration() {
208     return [
209       'label_display' => FALSE,
210       'formatter' => [
211         'label' => 'above',
212         'type' => $this->pluginDefinition['default_formatter'],
213         'settings' => [],
214         'third_party_settings' => [],
215       ],
216     ];
217   }
218
219   /**
220    * {@inheritdoc}
221    */
222   public function blockForm($form, FormStateInterface $form_state) {
223     $config = $this->getConfiguration();
224
225     $form['formatter'] = [
226       '#tree' => TRUE,
227       '#process' => [
228         [$this, 'formatterSettingsProcessCallback'],
229       ],
230     ];
231     $form['formatter']['label'] = [
232       '#type' => 'select',
233       '#title' => $this->t('Label'),
234       // @todo This is directly copied from
235       //   \Drupal\field_ui\Form\EntityViewDisplayEditForm::getFieldLabelOptions(),
236       //   resolve this in https://www.drupal.org/project/drupal/issues/2933924.
237       '#options' => [
238         'above' => $this->t('Above'),
239         'inline' => $this->t('Inline'),
240         'hidden' => '- ' . $this->t('Hidden') . ' -',
241         'visually_hidden' => '- ' . $this->t('Visually Hidden') . ' -',
242       ],
243       '#default_value' => $config['formatter']['label'],
244     ];
245
246     $form['formatter']['type'] = [
247       '#type' => 'select',
248       '#title' => $this->t('Formatter'),
249       '#options' => $this->getApplicablePluginOptions($this->getFieldDefinition()),
250       '#required' => TRUE,
251       '#default_value' => $config['formatter']['type'],
252       '#ajax' => [
253         'callback' => [static::class, 'formatterSettingsAjaxCallback'],
254         'wrapper' => 'formatter-settings-wrapper',
255       ],
256     ];
257
258     // Add the formatter settings to the form via AJAX.
259     $form['formatter']['settings_wrapper'] = [
260       '#prefix' => '<div id="formatter-settings-wrapper">',
261       '#suffix' => '</div>',
262     ];
263
264     return $form;
265   }
266
267   /**
268    * Render API callback: builds the formatter settings elements.
269    */
270   public function formatterSettingsProcessCallback(array &$element, FormStateInterface $form_state, array &$complete_form) {
271     if ($formatter = $this->getFormatter($element['#parents'], $form_state)) {
272       $element['settings_wrapper']['settings'] = $formatter->settingsForm($complete_form, $form_state);
273       $element['settings_wrapper']['settings']['#parents'] = array_merge($element['#parents'], ['settings']);
274       $element['settings_wrapper']['third_party_settings'] = $this->thirdPartySettingsForm($formatter, $this->getFieldDefinition(), $complete_form, $form_state);
275       $element['settings_wrapper']['third_party_settings']['#parents'] = array_merge($element['#parents'], ['third_party_settings']);
276
277       // Store the array parents for our element so that we can retrieve the
278       // formatter settings in our AJAX callback.
279       $form_state->set('field_block_array_parents', $element['#array_parents']);
280     }
281     return $element;
282   }
283
284   /**
285    * Adds the formatter third party settings forms.
286    *
287    * @param \Drupal\Core\Field\FormatterInterface $plugin
288    *   The formatter.
289    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
290    *   The field definition.
291    * @param array $form
292    *   The (entire) configuration form array.
293    * @param \Drupal\Core\Form\FormStateInterface $form_state
294    *   The form state.
295    *
296    * @return array
297    *   The formatter third party settings form.
298    */
299   protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
300     $settings_form = [];
301     // Invoke hook_field_formatter_third_party_settings_form(), keying resulting
302     // subforms by module name.
303     foreach ($this->moduleHandler->getImplementations('field_formatter_third_party_settings_form') as $module) {
304       $settings_form[$module] = $this->moduleHandler->invoke($module, 'field_formatter_third_party_settings_form', [
305         $plugin,
306         $field_definition,
307         EntityDisplayBase::CUSTOM_MODE,
308         $form,
309         $form_state,
310       ]);
311     }
312     return $settings_form;
313   }
314
315   /**
316    * Render API callback: gets the layout settings elements.
317    */
318   public static function formatterSettingsAjaxCallback(array $form, FormStateInterface $form_state) {
319     $formatter_array_parents = $form_state->get('field_block_array_parents');
320     return NestedArray::getValue($form, array_merge($formatter_array_parents, ['settings_wrapper']));
321   }
322
323   /**
324    * {@inheritdoc}
325    */
326   public function blockSubmit($form, FormStateInterface $form_state) {
327     $this->configuration['formatter'] = $form_state->getValue('formatter');
328   }
329
330   /**
331    * Gets the field definition.
332    *
333    * @return \Drupal\Core\Field\FieldDefinitionInterface
334    *   The field definition.
335    */
336   protected function getFieldDefinition() {
337     if (empty($this->fieldDefinition)) {
338       $field_definitions = $this->entityFieldManager->getFieldDefinitions($this->entityTypeId, $this->bundle);
339       $this->fieldDefinition = $field_definitions[$this->fieldName];
340     }
341     return $this->fieldDefinition;
342   }
343
344   /**
345    * Returns an array of applicable formatter options for a field.
346    *
347    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
348    *   The field definition.
349    *
350    * @return array
351    *   An array of applicable formatter options.
352    *
353    * @see \Drupal\field_ui\Form\EntityDisplayFormBase::getApplicablePluginOptions()
354    */
355   protected function getApplicablePluginOptions(FieldDefinitionInterface $field_definition) {
356     $options = $this->formatterManager->getOptions($field_definition->getType());
357     $applicable_options = [];
358     foreach ($options as $option => $label) {
359       $plugin_class = DefaultFactory::getPluginClass($option, $this->formatterManager->getDefinition($option));
360       if ($plugin_class::isApplicable($field_definition)) {
361         $applicable_options[$option] = $label;
362       }
363     }
364     return $applicable_options;
365   }
366
367   /**
368    * Gets the formatter object.
369    *
370    * @param array $parents
371    *   The #parents of the element representing the formatter.
372    * @param \Drupal\Core\Form\FormStateInterface $form_state
373    *   The current state of the form.
374    *
375    * @return \Drupal\Core\Field\FormatterInterface
376    *   The formatter object.
377    */
378   protected function getFormatter(array $parents, FormStateInterface $form_state) {
379     // Use the processed values, if available.
380     $configuration = NestedArray::getValue($form_state->getValues(), $parents);
381     if (!$configuration) {
382       // Next check the raw user input.
383       $configuration = NestedArray::getValue($form_state->getUserInput(), $parents);
384       if (!$configuration) {
385         // If no user input exists, use the default values.
386         $configuration = $this->getConfiguration()['formatter'];
387       }
388     }
389
390     return $this->formatterManager->getInstance([
391       'configuration' => $configuration,
392       'field_definition' => $this->getFieldDefinition(),
393       'view_mode' => EntityDisplayBase::CUSTOM_MODE,
394       'prepare' => TRUE,
395     ]);
396   }
397
398 }