FixedBlockContentBlock.php in Fixed Block Content 8
File
src/Plugin/Block/FixedBlockContentBlock.php
View source
<?php
namespace Drupal\fixed_block_content\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\fixed_block_content\Entity\FixedBlockContent;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
class FixedBlockContentBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $entityTypeManager;
protected $entityDisplayRepository;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepositoryInterface $entity_display_repository) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->entityDisplayRepository = $entity_display_repository;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'), $container
->get('entity_display.repository'));
}
public function build() {
$output = [];
if (($fixed_block = FixedBlockContent::load($this
->getDerivativeId())) && ($block_content = $fixed_block
->getBlockContent())) {
$output = $this->entityTypeManager
->getViewBuilder('block_content')
->view($block_content, isset($this->configuration['view_mode']) ? $this->configuration['view_mode'] : '');
}
return $output;
}
public function blockForm($form, FormStateInterface $form_state) {
$fixed_block = FixedBlockContent::load($this
->getDerivativeId());
$options = $this->entityDisplayRepository
->getViewModeOptionsByBundle('block_content', $fixed_block
->getBlockContentBundle());
$form['view_mode'] = [
'#type' => 'select',
'#options' => $options,
'#title' => $this
->t('View mode'),
'#description' => $this
->t('Output the block in this view mode.'),
'#default_value' => isset($this->configuration['view_mode']) ? $this->configuration['view_mode'] : '',
'#access' => count($options) > 1,
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['view_mode'] = $form_state
->getValue('view_mode');
}
public function getCacheTags() {
$cache_tags = parent::getCacheTags();
if ($fixed_block = FixedBlockContent::load($this
->getDerivativeId())) {
$cache_tags = Cache::mergeTags($cache_tags, $fixed_block
->getCacheTags());
$cache_tags = Cache::mergeTags($cache_tags, $fixed_block
->getBlockContent()
->getCacheTags());
}
return $cache_tags;
}
}