class FieldBlock
Same name in this branch
- 9 core/modules/layout_builder/tests/modules/layout_builder_fieldblock_test/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder_fieldblock_test\Plugin\Block\FieldBlock
Same name in other branches
- 8.9.x core/modules/layout_builder/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder\Plugin\Block\FieldBlock
- 8.9.x core/modules/layout_builder/tests/modules/layout_builder_fieldblock_test/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder_fieldblock_test\Plugin\Block\FieldBlock
- 10 core/modules/layout_builder/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder\Plugin\Block\FieldBlock
- 10 core/modules/layout_builder/tests/modules/layout_builder_fieldblock_test/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder_fieldblock_test\Plugin\Block\FieldBlock
- 11.x core/modules/layout_builder/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder\Plugin\Block\FieldBlock
- 11.x core/modules/layout_builder/tests/modules/layout_builder_fieldblock_test/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder_fieldblock_test\Plugin\Block\FieldBlock
Provides a block that renders a field from an entity.
@Block( id = "field_block", deriver = "\Drupal\layout_builder\Plugin\Derivative\FieldBlockDeriver", )
@internal Plugin classes are internal.
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements \Drupal\Component\Plugin\PluginInspectionInterface, \Drupal\Component\Plugin\DerivativeInspectionInterface
- class \Drupal\Core\Plugin\PluginBase extends \Drupal\Component\Plugin\PluginBase uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Messenger\MessengerTrait
- class \Drupal\Core\Block\BlockBase extends \Drupal\Core\Plugin\PluginBase implements \Drupal\Core\Block\BlockPluginInterface, \Drupal\Core\Plugin\PluginWithFormsInterface, \Drupal\Core\Plugin\PreviewAwarePluginInterface, \Drupal\Core\Render\PreviewFallbackInterface, \Drupal\Core\Plugin\ContextAwarePluginInterface uses \Drupal\Core\Block\BlockPluginTrait, \Drupal\Core\Plugin\ContextAwarePluginTrait, \Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait
- class \Drupal\layout_builder\Plugin\Block\FieldBlock extends \Drupal\Core\Block\BlockBase implements \Drupal\Core\Plugin\ContextAwarePluginInterface, \Drupal\Core\Plugin\ContainerFactoryPluginInterface
- class \Drupal\Core\Block\BlockBase extends \Drupal\Core\Plugin\PluginBase implements \Drupal\Core\Block\BlockPluginInterface, \Drupal\Core\Plugin\PluginWithFormsInterface, \Drupal\Core\Plugin\PreviewAwarePluginInterface, \Drupal\Core\Render\PreviewFallbackInterface, \Drupal\Core\Plugin\ContextAwarePluginInterface uses \Drupal\Core\Block\BlockPluginTrait, \Drupal\Core\Plugin\ContextAwarePluginTrait, \Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait
- class \Drupal\Core\Plugin\PluginBase extends \Drupal\Component\Plugin\PluginBase uses \Drupal\Core\StringTranslation\StringTranslationTrait, \Drupal\Core\DependencyInjection\DependencySerializationTrait, \Drupal\Core\Messenger\MessengerTrait
Expanded class hierarchy of FieldBlock
2 files declare their use of FieldBlock
- FieldBlock.php in core/
modules/ layout_builder/ tests/ modules/ layout_builder_fieldblock_test/ src/ Plugin/ Block/ FieldBlock.php - FieldBlockTest.php in core/
modules/ layout_builder/ tests/ src/ Kernel/ FieldBlockTest.php
File
-
core/
modules/ layout_builder/ src/ Plugin/ Block/ FieldBlock.php, line 38
Namespace
Drupal\layout_builder\Plugin\BlockView source
class FieldBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The formatter manager.
*
* @var \Drupal\Core\Field\FormatterPluginManager
*/
protected $formatterManager;
/**
* The entity type ID.
*
* @var string
*/
protected $entityTypeId;
/**
* The bundle ID.
*
* @var string
*/
protected $bundle;
/**
* The field name.
*
* @var string
*/
protected $fieldName;
/**
* The field definition.
*
* @var \Drupal\Core\Field\FieldDefinitionInterface
*/
protected $fieldDefinition;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The logger.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Constructs a new FieldBlock.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
* @param \Drupal\Core\Field\FormatterPluginManager $formatter_manager
* The formatter manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Psr\Log\LoggerInterface $logger
* The 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;
// Get the entity type and field name from the plugin ID.
[
,
$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);
}
/**
* {@inheritdoc}
*/
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'));
}
/**
* Gets the entity that has the field.
*
* @return \Drupal\Core\Entity\FieldableEntityInterface
* The entity.
*/
protected function getEntity() {
return $this->getContextValue('entity');
}
/**
* {@inheritdoc}
*/
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;
}
/**
* {@inheritdoc}
*/
public function getPreviewFallbackString() {
return new TranslatableMarkup('"@field" field', [
'@field' => $this->getFieldDefinition()
->getLabel(),
]);
}
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
$entity = $this->getEntity();
// First consult the entity.
$access = $entity->access('view', $account, TRUE);
if (!$access->isAllowed()) {
return $access;
}
// Check that the entity in question has this field.
if (!$entity instanceof FieldableEntityInterface || !$entity->hasField($this->fieldName)) {
return $access->andIf(AccessResult::forbidden());
}
// Check field access.
$field = $entity->get($this->fieldName);
$access = $access->andIf($field->access('view', $account, TRUE));
if (!$access->isAllowed()) {
return $access;
}
// Check to see if the field has any values or a default value.
if ($field->isEmpty() && !$field->getFieldDefinition()
->getDefaultValue($entity)) {
// @todo Remove special handling of image fields after
// https://www.drupal.org/project/drupal/issues/3005528.
if ($field->getFieldDefinition()
->getType() === 'image' && $field->getFieldDefinition()
->getSetting('default_image')) {
return $access;
}
return $access->andIf(AccessResult::forbidden());
}
return $access;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'label_display' => FALSE,
'formatter' => [
'label' => 'above',
'type' => $this->pluginDefinition['default_formatter'],
'settings' => [],
'third_party_settings' => [],
],
];
}
/**
* {@inheritdoc}
*/
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'),
// @todo This is directly copied from
// \Drupal\field_ui\Form\EntityViewDisplayEditForm::getFieldLabelOptions(),
// resolve this in https://www.drupal.org/project/drupal/issues/2933924.
'#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',
],
];
// Add the formatter settings to the form via AJAX.
$form['formatter']['settings_wrapper'] = [
'#prefix' => '<div id="formatter-settings-wrapper">',
'#suffix' => '</div>',
];
return $form;
}
/**
* Render API callback: builds the formatter settings elements.
*/
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]');
// Store the array parents for our element so that we can retrieve the
// formatter settings in our AJAX callback.
$form_state->set('field_block_array_parents', $element['#array_parents']);
}
return $element;
}
/**
* Adds the formatter third party settings forms.
*
* @param \Drupal\Core\Field\FormatterInterface $plugin
* The formatter.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
* @param array $form
* The (entire) configuration form array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The formatter third party settings form.
*/
protected function thirdPartySettingsForm(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
$settings_form = [];
// Invoke hook_field_formatter_third_party_settings_form(), keying resulting
// subforms by module name.
$this->moduleHandler
->invokeAllWith('field_formatter_third_party_settings_form', function (callable $hook, string $module) use (&$settings_form, $plugin, $field_definition, $form, $form_state) {
$settings_form[$module] = $hook($plugin, $field_definition, EntityDisplayBase::CUSTOM_MODE, $form, $form_state);
});
return $settings_form;
}
/**
* Render API callback: gets the layout settings elements.
*/
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',
]));
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['formatter'] = $form_state->getValue('formatter');
}
/**
* Gets the field definition.
*
* @return \Drupal\Core\Field\FieldDefinitionInterface
* The field definition.
*/
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;
}
/**
* Returns an array of applicable formatter options for a field.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
*
* @return array
* An array of applicable formatter options.
*
* @see \Drupal\field_ui\Form\EntityDisplayFormBase::getApplicablePluginOptions()
*/
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;
}
/**
* Gets the formatter object.
*
* @param array $parents
* The #parents of the element representing the formatter.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return \Drupal\Core\Field\FormatterInterface
* The formatter object.
*/
protected function getFormatter(array $parents, FormStateInterface $form_state) {
// Use the processed values, if available.
$configuration = NestedArray::getValue($form_state->getValues(), $parents);
if (!$configuration) {
// Next check the raw user input.
$configuration = NestedArray::getValue($form_state->getUserInput(), $parents);
if (!$configuration) {
// If no user input exists, use the default values.
$configuration = $this->getConfiguration()['formatter'];
}
}
return $this->formatterManager
->getInstance([
'configuration' => $configuration,
'field_definition' => $this->getFieldDefinition(),
'view_mode' => EntityDisplayBase::CUSTOM_MODE,
'prepare' => TRUE,
]);
}
}
Members
Title Sort descending | Modifiers | Object type | Summary | Member alias | Overriden Title | Overrides |
---|---|---|---|---|---|---|
BlockBase::buildConfigurationForm | public | function | Form constructor. | Overrides PluginFormInterface::buildConfigurationForm | 2 | |
BlockPluginInterface::BLOCK_LABEL_VISIBLE | constant | Indicates the block label (title) should be displayed to end users. | ||||
BlockPluginTrait::$inPreview | protected | property | Whether the plugin is being rendered in preview mode. | |||
BlockPluginTrait::$transliteration | protected | property | The transliteration service. | |||
BlockPluginTrait::access | public | function | ||||
BlockPluginTrait::baseConfigurationDefaults | protected | function | Returns generic default configuration for block plugins. | |||
BlockPluginTrait::blockValidate | public | function | 3 | |||
BlockPluginTrait::buildConfigurationForm | public | function | Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. |
Aliased as: traitBuildConfigurationForm | ||
BlockPluginTrait::calculateDependencies | public | function | ||||
BlockPluginTrait::getConfiguration | public | function | 1 | |||
BlockPluginTrait::getMachineNameSuggestion | public | function | 1 | |||
BlockPluginTrait::label | public | function | ||||
BlockPluginTrait::setConfiguration | public | function | ||||
BlockPluginTrait::setConfigurationValue | public | function | ||||
BlockPluginTrait::setInPreview | public | function | ||||
BlockPluginTrait::setTransliteration | public | function | Sets the transliteration service. | |||
BlockPluginTrait::submitConfigurationForm | public | function | Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit(). |
|||
BlockPluginTrait::transliteration | protected | function | Wraps the transliteration service. | |||
BlockPluginTrait::validateConfigurationForm | public | function | Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). |
1 | ||
ContextAwarePluginAssignmentTrait::addContextAssignmentElement | protected | function | Builds a form element for assigning a context to a given slot. | |||
ContextAwarePluginAssignmentTrait::contextHandler | protected | function | Wraps the context handler. | |||
ContextAwarePluginTrait::$context | protected | property | The data objects representing the context of this plugin. | |||
ContextAwarePluginTrait::$initializedContextConfig | protected | property | Tracks whether the context has been initialized from configuration. | |||
ContextAwarePluginTrait::getCacheContexts | public | function | 9 | |||
ContextAwarePluginTrait::getCacheMaxAge | public | function | 7 | |||
ContextAwarePluginTrait::getCacheTags | public | function | 4 | |||
ContextAwarePluginTrait::getContext | public | function | ||||
ContextAwarePluginTrait::getContextDefinition | public | function | ||||
ContextAwarePluginTrait::getContextDefinitions | public | function | ||||
ContextAwarePluginTrait::getContextMapping | public | function | ||||
ContextAwarePluginTrait::getContexts | public | function | ||||
ContextAwarePluginTrait::getContextValue | public | function | ||||
ContextAwarePluginTrait::getContextValues | public | function | ||||
ContextAwarePluginTrait::getPluginDefinition | abstract public | function | 1 | |||
ContextAwarePluginTrait::setContext | public | function | 1 | |||
ContextAwarePluginTrait::setContextMapping | public | function | ||||
ContextAwarePluginTrait::setContextValue | public | function | ||||
ContextAwarePluginTrait::validateContexts | public | function | ||||
DerivativeInspectionInterface::getBaseId | public | function | Gets the base_plugin_id of the plugin instance. | 1 | ||
DerivativeInspectionInterface::getDerivativeId | public | function | Gets the derivative_id of the plugin instance. | 1 | ||
FieldBlock::$bundle | protected | property | The bundle ID. | |||
FieldBlock::$entityFieldManager | protected | property | The entity field manager. | |||
FieldBlock::$entityTypeId | protected | property | The entity type ID. | |||
FieldBlock::$fieldDefinition | protected | property | The field definition. | |||
FieldBlock::$fieldName | protected | property | The field name. | |||
FieldBlock::$formatterManager | protected | property | The formatter manager. | |||
FieldBlock::$logger | protected | property | The logger. | |||
FieldBlock::$moduleHandler | protected | property | The module handler. | |||
FieldBlock::blockAccess | protected | function | Indicates whether the block should be shown. | Overrides BlockPluginTrait::blockAccess | ||
FieldBlock::blockForm | public | function | Overrides BlockPluginTrait::blockForm | |||
FieldBlock::blockSubmit | public | function | Overrides BlockPluginTrait::blockSubmit | |||
FieldBlock::build | public | function | Builds and returns the renderable array for this block plugin. | Overrides BlockPluginInterface::build | ||
FieldBlock::create | public static | function | Creates an instance of the plugin. | Overrides ContainerFactoryPluginInterface::create | ||
FieldBlock::defaultConfiguration | public | function | Overrides BlockPluginTrait::defaultConfiguration | |||
FieldBlock::formatterSettingsAjaxCallback | public static | function | Render API callback: gets the layout settings elements. | |||
FieldBlock::formatterSettingsProcessCallback | public | function | Render API callback: builds the formatter settings elements. | |||
FieldBlock::getApplicablePluginOptions | protected | function | Returns an array of applicable formatter options for a field. | |||
FieldBlock::getEntity | protected | function | Gets the entity that has the field. | |||
FieldBlock::getFieldDefinition | protected | function | Gets the field definition. | |||
FieldBlock::getFormatter | protected | function | Gets the formatter object. | |||
FieldBlock::getPreviewFallbackString | public | function | Overrides BlockPluginTrait::getPreviewFallbackString | |||
FieldBlock::thirdPartySettingsForm | protected | function | Adds the formatter third party settings forms. | |||
FieldBlock::__construct | public | function | Constructs a new FieldBlock. | Overrides BlockPluginTrait::__construct | ||
MessengerTrait::$messenger | protected | property | The messenger. | 17 | ||
MessengerTrait::messenger | public | function | Gets the messenger. | 17 | ||
MessengerTrait::setMessenger | public | function | Sets the messenger. | |||
PluginInspectionInterface::getPluginId | public | function | Gets the plugin_id of the plugin instance. | 2 | ||
PluginWithFormsTrait::getFormClass | public | function | Implements \Drupal\Core\Plugin\PluginWithFormsInterface::getFormClass(). | |||
PluginWithFormsTrait::hasFormClass | public | function | Implements \Drupal\Core\Plugin\PluginWithFormsInterface::hasFormClass(). | |||
StringTranslationTrait::$stringTranslation | protected | property | The string translation service. | 3 | ||
StringTranslationTrait::formatPlural | protected | function | Formats a string containing a count of items. | |||
StringTranslationTrait::getNumberOfPlurals | protected | function | Returns the number of plurals supported by a given language. | |||
StringTranslationTrait::getStringTranslation | protected | function | Gets the string translation service. | |||
StringTranslationTrait::setStringTranslation | public | function | Sets the string translation service to use. | 2 | ||
StringTranslationTrait::t | protected | function | Translates a string to the current language or to a given language. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.