BlockFieldLabelFormatter.php in Block field 8
File
src/Plugin/Field/FieldFormatter/BlockFieldLabelFormatter.php
View source
<?php
namespace Drupal\block_field\Plugin\Field\FieldFormatter;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BlockFieldLabelFormatter extends FormatterBase {
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountProxyInterface $current_user) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->currentUser = $current_user;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
->get('current_user'));
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$block_instance = $item
->getBlock();
if (!$block_instance) {
continue;
}
$access = $block_instance
->access($this->currentUser
->getAccount(), TRUE);
CacheableMetadata::createFromRenderArray($elements)
->addCacheableDependency($access)
->applyTo($elements);
if (!$access
->isAllowed()) {
continue;
}
$elements[$delta] = [
'#markup' => $block_instance
->label(),
];
CacheableMetadata::createFromRenderArray($elements[$delta])
->addCacheableDependency($block_instance)
->applyTo($elements[$delta]);
}
return $elements;
}
}