EntityView.php in Chaos Tool Suite (ctools) 8.3
File
src/Plugin/Block/EntityView.php
View source
<?php
namespace Drupal\ctools\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class EntityView extends BlockBase implements ContextAwarePluginInterface, 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 defaultConfiguration() {
return [
'view_mode' => 'default',
];
}
public function blockForm($form, FormStateInterface $form_state) {
$form['view_mode'] = [
'#type' => 'select',
'#options' => $this->entityDisplayRepository
->getViewModeOptions($this
->getDerivativeId()),
'#title' => $this
->t('View mode'),
'#default_value' => $this->configuration['view_mode'],
];
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['view_mode'] = $form_state
->getValue('view_mode');
}
public function access(AccountInterface $account, $return_as_object = FALSE) {
$parent_access = parent::access($account, TRUE);
if (!$parent_access
->isAllowed()) {
return $return_as_object ? $parent_access : $parent_access
->isAllowed();
}
$entity = $this
->getContextValue('entity');
return $entity
->access('view', $account, $return_as_object);
}
public function build() {
$entity = $this
->getContextValue('entity');
$view_builder = $this->entityTypeManager
->getViewBuilder($entity
->getEntityTypeId());
$build = $view_builder
->view($entity, $this->configuration['view_mode']);
CacheableMetadata::createFromObject($entity)
->merge(CacheableMetadata::createFromRenderArray($build))
->applyTo($build);
return $build;
}
}
Classes
Name |
Description |
EntityView |
Provides a block to view a specific entity. |