ParagraphBlock.php in Paragraph blocks 8.2
File
src/Plugin/Block/ParagraphBlock.php
View source
<?php
namespace Drupal\paragraph_blocks\Plugin\Block;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\CacheableMetadata;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ParagraphBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {
protected $entityTypeId;
protected $fieldName;
protected $fieldDelta;
protected $entityTypeManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
list(, $entity_type_id, $field_name, $field_delta) = explode(':', $plugin_id);
$this->entityTypeId = $entity_type_id;
$this->fieldName = $field_name;
$this->fieldDelta = $field_delta;
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
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'));
}
public function build() {
$paragraph = NULL;
$entity = $this
->getContextEntity();
if ($entity) {
$referenced_entities = $entity
->get($this->fieldName)
->referencedEntities();
if (isset($referenced_entities[$this->fieldDelta])) {
$paragraph = $referenced_entities[$this->fieldDelta];
}
}
if (!$paragraph) {
return [
'#markup' => $this
->t('This block is broken. The Content group or the paragraph does not exist.'),
];
}
$view_builder = $this->entityTypeManager
->getViewBuilder($paragraph
->getEntityTypeId());
$build = $view_builder
->view($paragraph, 'default');
if (function_exists('geysir_contextual_links')) {
$link_options = [
'parent_entity_type' => $entity
->getEntityType()
->id(),
'parent_entity' => $entity
->id(),
'field' => $this->fieldName,
'field_wrapper_id' => Html::getUniqueId('geysir--' . $this->fieldName),
'delta' => $this->fieldDelta,
'js' => 'nojs',
'paragraph' => $paragraph
->id(),
];
$build['#geysir_field_paragraph_links'] = geysir_contextual_links($link_options);
$build['#theme_wrappers'][] = 'geysir_field_paragraph_wrapper';
$build['#attributes']['data-geysir-field-paragraph-field-wrapper'] = $link_options['field_wrapper_id'];
}
CacheableMetadata::createFromObject($this
->getContext('entity'))
->applyTo($build);
return $build;
}
protected function getContextEntity() {
return $this
->getContextValue('entity');
}
}