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\Session\AccountInterface;
21 use Drupal\Core\StringTranslation\TranslatableMarkup;
22 use Psr\Log\LoggerInterface;
23 use Symfony\Component\DependencyInjection\ContainerInterface;
26 * Provides a block that renders a field from an entity.
30 * deriver = "\Drupal\layout_builder\Plugin\Derivative\FieldBlockDeriver",
33 class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
36 * The entity field manager.
38 * @var \Drupal\Core\Entity\EntityFieldManagerInterface
40 protected $entityFieldManager;
43 * The formatter manager.
45 * @var \Drupal\Core\Field\FormatterPluginManager
47 protected $formatterManager;
54 protected $entityTypeId;
71 * The field definition.
73 * @var \Drupal\Core\Field\FieldDefinitionInterface
75 protected $fieldDefinition;
80 * @var \Drupal\Core\Extension\ModuleHandlerInterface
82 protected $moduleHandler;
87 * @var \Psr\Log\LoggerInterface
92 * Constructs a new FieldBlock.
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
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;
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;
121 parent::__construct($configuration, $plugin_id, $plugin_definition);
127 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $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')
140 * Gets the entity that has the field.
142 * @return \Drupal\Core\Entity\FieldableEntityInterface
145 protected function getEntity() {
146 return $this->getContextValue('entity');
152 public function build() {
153 $display_settings = $this->getConfiguration()['formatter'];
154 $entity = $this->getEntity();
156 $build = $entity->get($this->fieldName)->view($display_settings);
158 catch (\Exception $e) {
160 $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]);
162 CacheableMetadata::createFromObject($this)->applyTo($build);
169 public function getPreviewFallbackString() {
170 return new TranslatableMarkup('Placeholder for the "@field" field', ['@field' => $this->getFieldDefinition()->getLabel()]);
176 protected function blockAccess(AccountInterface $account) {
177 $entity = $this->getEntity();
179 // First consult the entity.
180 $access = $entity->access('view', $account, TRUE);
181 if (!$access->isAllowed()) {
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());
190 // Check field access.
191 $field = $entity->get($this->fieldName);
192 $access = $access->andIf($field->access('view', $account, TRUE));
193 if (!$access->isAllowed()) {
197 // Check to see if the field has any values.
198 if ($field->isEmpty()) {
199 return $access->andIf(AccessResult::forbidden());
207 public function defaultConfiguration() {
209 'label_display' => FALSE,
212 'type' => $this->pluginDefinition['default_formatter'],
214 'third_party_settings' => [],
222 public function blockForm($form, FormStateInterface $form_state) {
223 $config = $this->getConfiguration();
225 $form['formatter'] = [
228 [$this, 'formatterSettingsProcessCallback'],
231 $form['formatter']['label'] = [
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.
238 'above' => $this->t('Above'),
239 'inline' => $this->t('Inline'),
240 'hidden' => '- ' . $this->t('Hidden') . ' -',
241 'visually_hidden' => '- ' . $this->t('Visually Hidden') . ' -',
243 '#default_value' => $config['formatter']['label'],
246 $form['formatter']['type'] = [
248 '#title' => $this->t('Formatter'),
249 '#options' => $this->getApplicablePluginOptions($this->getFieldDefinition()),
251 '#default_value' => $config['formatter']['type'],
253 'callback' => [static::class, 'formatterSettingsAjaxCallback'],
254 'wrapper' => 'formatter-settings-wrapper',
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>',
268 * Render API callback: builds the formatter settings elements.
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']);
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']);
285 * Adds the formatter third party settings forms.
287 * @param \Drupal\Core\Field\FormatterInterface $plugin
289 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
290 * The field definition.
292 * The (entire) configuration form array.
293 * @param \Drupal\Core\Form\FormStateInterface $form_state
297 * The formatter third party settings form.
299 protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
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', [
307 EntityDisplayBase::CUSTOM_MODE,
312 return $settings_form;
316 * Render API callback: gets the layout settings elements.
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']));
326 public function blockSubmit($form, FormStateInterface $form_state) {
327 $this->configuration['formatter'] = $form_state->getValue('formatter');
331 * Gets the field definition.
333 * @return \Drupal\Core\Field\FieldDefinitionInterface
334 * The field definition.
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];
341 return $this->fieldDefinition;
345 * Returns an array of applicable formatter options for a field.
347 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
348 * The field definition.
351 * An array of applicable formatter options.
353 * @see \Drupal\field_ui\Form\EntityDisplayFormBase::getApplicablePluginOptions()
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;
364 return $applicable_options;
368 * Gets the formatter object.
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.
375 * @return \Drupal\Core\Field\FormatterInterface
376 * The formatter object.
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'];
390 return $this->formatterManager->getInstance([
391 'configuration' => $configuration,
392 'field_definition' => $this->getFieldDefinition(),
393 'view_mode' => EntityDisplayBase::CUSTOM_MODE,