public function BlockFieldFormatter::viewElements in Block field 8
Builds a renderable array for a field value.
Parameters
\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.
string $langcode: The language that should be used to render the field.
Return value
array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.
Overrides FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ BlockFieldFormatter.php, line 112
Class
- BlockFieldFormatter
- Plugin implementation of the 'block_field' formatter.
Namespace
Drupal\block_field\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
/** @var \Drupal\block_field\BlockFieldItemInterface $item */
$block_instance = $item
->getBlock();
// Inject runtime contexts.
if ($block_instance instanceof ContextAwarePluginInterface) {
try {
$contexts = $this->contextRepository
->getRuntimeContexts($block_instance
->getContextMapping());
$this->contextHandler
->applyContextMapping($block_instance, $contexts);
} catch (ContextException $e) {
continue;
}
}
// Make sure the block exists and is accessible.
if (!$block_instance) {
continue;
}
$access = $block_instance
->access($this->currentUser
->getAccount(), TRUE);
CacheableMetadata::createFromRenderArray($elements)
->addCacheableDependency($access)
->applyTo($elements);
if (!$access
->isAllowed()) {
continue;
}
// See \Drupal\block\BlockViewBuilder::buildPreRenderableBlock
// See template_preprocess_block()
$base_id = $block_instance
->getBaseId();
$elements[$delta] = [
'#theme' => 'block',
'#attributes' => [],
'#configuration' => $block_instance
->getConfiguration(),
'#plugin_id' => $block_instance
->getPluginId(),
'#base_plugin_id' => $base_id,
'#derivative_plugin_id' => $block_instance
->getDerivativeId(),
'#id' => $block_instance
->getMachineNameSuggestion(),
'#pre_render' => [
[
$this,
'preRender',
],
],
'#block' => $block_instance,
];
CacheableMetadata::createFromRenderArray($elements[$delta])
->addCacheableDependency($block_instance)
->applyTo($elements[$delta]);
// If an alter hook wants to modify the block contents, it can append
// another #pre_render hook.
$this->moduleHandler
->alter([
'block_view',
"block_view_{$base_id}",
], $elements[$delta], $block_instance);
// Allow altering of cacheability metadata or setting #create_placeholder.
$this->moduleHandler
->alter([
'block_build',
"block_build_{$base_id}",
], $elements[$delta], $block_instance);
}
return $elements;
}