htools-8.x-1.x-dev/src/Plugin/Block/ProcessedTextEntityBlock.php

src/Plugin/Block/ProcessedTextEntityBlock.php
<?php

namespace Drupal\htools\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Utility\Token;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Provides a 'ProcessedTextBlock' block.
 *
 * @Block(
 *  id = "processed_text_entity",
 *  category = @Translation("Hiberus tools"),
 *  deriver = "\Drupal\htools\Plugin\Derivative\EntityTypeBlockDeriver",
 * )
 *
 * @internal
 *   Plugin classes are internal.
 */
class ProcessedTextEntityBlock extends BlockBase implements ContextAwarePluginInterface, ContainerFactoryPluginInterface {

  /**
   * The token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * The entity type ID.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * The entity type manager.
   *
   * @var string
   */
  protected $entityTypeManager;

  /**
   * Constructs a new ProcessedTextEntityBlock object.
   *
   * @param array $configuration
   *   The plugin configuration.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin definition.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The token service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Token $token, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->token = $token;
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('token'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $plugin_id = $this->pluginId;
    $entity_type = str_replace('processed_text_entity:', '', $plugin_id);
    $settings = $this->getConfiguration();
    $form['content'] = [
      '#title' => $this->t('Content'),
      '#type' => 'text_format',
      '#default_value' => !empty($settings['content']['value']) ? $settings['content']['value'] : NULL,
      '#format' => !empty($settings['content']['format']) ? $settings['content']['format'] : filter_default_format(),
      '#token_types' => [$this->getTokenType($entity_type)],
      '#element_validate' => ['token_element_validate'],
      '#after_build' => ['token_element_validate'],
    ];
    // Show the token help relevant to this pattern type.
    $form['token_help'] = [
      '#theme' => 'token_tree_link',
      '#token_types' => [$this->getTokenType($entity_type)],
    ];
    $form['fields'] = [
      '#title' => $this->t('Fields'),
      '#type' => 'textarea',
      '#default_value' => !empty($settings['fields']) ? $settings['fields'] : NULL,
      '#placeholder' => $this->t('Enter field machine names, one per line.'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $hasValues = FALSE;
    $entity = $this->getEntity();
    $entity_type = $entity->getEntityTypeId();
    $settings = $this->getConfiguration();

    if (!empty($settings['fields'])) {

      $lines = explode("\n", $settings['fields']);
      foreach ($lines as $field_id) {

        $field_id = trim($field_id);
        $field_id = preg_replace('/\s+/', '', $field_id);

        if ($entity->hasField($field_id)) {
          if (!$entity->get($field_id)->isEmpty()) {
            $hasValues = TRUE;
          }
        }
      }
    }
    if (!empty($settings['content']['value'])) {
      $content = $settings['content']['value'];
      $element = [
        '#type' => 'processed_text',
        '#text' => $this->token->replace($content, [$this->getTokenType($entity_type) => $entity], ['clear' => TRUE]),
        '#format' => $settings['content']['format'],
        '#filter_types_to_skip' => [],
      ];
    }
    else {

      $element = [
        '#type' => 'processed_text',
        '#text' => '',
        '#access' => FALSE,
        '#filter_types_to_skip' => [],
      ];
    }
    if (!$hasValues) {
      $element['#access'] = FALSE;
    }
    // Return the render array.
    return $element;
  }

  /**
   * {@inheritdoc}
   *
   * Most block plugins should not override this method. To add submission
   * handling for a specific block type, override BlockBase::blockSubmit().
   *
   * @see \Drupal\Core\Block\BlockBase::blockSubmit()
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    if (!$form_state->getErrors()) {
      $this->configuration['content'] = $form_state->getValue('content');
      $this->configuration['fields'] = $form_state->getValue('fields');
    }
  }

  /**
   * Gets the entity.
   *
   * @return \Drupal\Core\Entity\FieldableEntityInterface
   *   The entity.
   */
  protected function getEntity() {
    return $this->getContextValue('entity');
  }

  /**
   * Gets the token type.
   *
   * @param string $entity_type
   *   The entity type.
   */
  protected function getTokenType(string $entity_type) {
    $entities = $this->entityTypeManager->getDefinitions();
    if (!empty($entities[$entity_type])) {
      return $entities[$entity_type]->get('token_type');
    }
    return NULL;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc