views_addons-1.1.0/src/Plugin/views/area/AddCoreEntity.php

src/Plugin/views/area/AddCoreEntity.php
<?php

namespace Drupal\views_addons\Plugin\views\area;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\views\Plugin\views\area\AreaPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides an area for adding entities provided by drupal core.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("views_addons_add_entity")
 */
class AddCoreEntity extends AreaPluginBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity type bundle info service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * Constructs a new AddEntity object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
  }

  /**
   * {@inheritdoc}
   */
  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_type.bundle.info')
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['entity_type'] = ['default' => 'node'];
    $options['bundle'] = ['default' => ''];
    $options['vocabulary'] = ['default' => ''];
    $options['css_classes'] = ['default' => ''];
    $options['link_text'] = ['default' => $this->t('Add new item')];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    $entity_types = [
      'node' => $this->t('Content (Node)'),
      'user' => $this->t('User'),
      'taxonomy_term' => $this->t('Taxonomy term'),
    ];

    $form['entity_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Entity Type'),
      '#options' => $entity_types,
      '#default_value' => $this->options['entity_type'],
      '#required' => TRUE,
    ];

    $form['bundle'] = [
      '#type' => 'select',
      '#title' => $this->t('Bundle'),
      '#options' => $this->getBundleOptions('node'),
      '#default_value' => $this->options['bundle'],
      '#required' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="options[entity_type]"]' => ['value' => 'node'],
        ],
        'required' => [
          ':input[name="options[entity_type]"]' => ['value' => 'node'],
        ],
      ],
    ];

    $form['vocabulary'] = [
      '#type' => 'select',
      '#title' => $this->t('Vocabulary'),
      '#options' => $this->getBundleOptions('taxonomy_term'),
      '#default_value' => $this->options['vocabulary'],
      '#required' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="options[entity_type]"]' => ['value' => 'taxonomy_term'],
        ],
        'required' => [
          ':input[name="options[entity_type]"]' => ['value' => 'taxonomy_term'],
        ],
      ],
    ];

    $form['link_text'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Link Text'),
      '#description' => $this->t('Enter the text for the link.'),
      '#default_value' => $this->options['link_text'],
    ];

    $form['css_classes'] = [
      '#type' => 'textfield',
      '#title' => $this->t('CSS Classes'),
      '#default_value' => $this->options['css_classes'],
    ];

    parent::buildOptionsForm($form, $form_state);
  }

  /**
   * Returns the bundle options for a given entity type.
   *
   * @param string $entity_type
   *   The entity type.
   *
   * @return array
   *   The bundle options.
   */
  public function getBundleOptions(string $entity_type) {
    $options = [];
    if ($entity_type == 'taxonomy_term') {
      // Fetch taxonomy vocabularies for taxonomy terms.
      $vocabularies = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple();
      foreach ($vocabularies as $vocabulary) {
        $options[$vocabulary->id()] = $vocabulary->label();
      }
    }
    elseif ($entity_type == 'node') {
      // Fetch content types for nodes.
      $types = $this->entityTypeManager->getStorage('node_type')->loadMultiple();
      foreach ($types as $type) {
        $options[$type->id()] = $type->label();
      }
    }
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function render($empty = FALSE) {
    $entity_type = $this->options['entity_type'];
    $bundle = $this->options['bundle'];
    $vocabulary = $this->options['vocabulary'];
    $css_classes = $this->options['css_classes'];
    $link_text = $this->options['link_text'];
    $route_name = '';
    $access = FALSE;
    $cache_tags = [];

    $view_id = $this->view->storage->id();
    $cache_tags[] = "config:views.view.{$view_id}";

    switch ($entity_type) {
      case 'node':
        if (!empty($bundle)) {
          $route_name = 'node.add';
          $route_parameters = ['node_type' => $bundle];
          // Check if user has access to create this node type.
          $access = $this->entityTypeManager->getAccessControlHandler('node')->createAccess($bundle, NULL, [], TRUE);
          $cache_tags[] = "node_type:{$bundle}";
        }
        break;

      case 'user':
        $route_name = 'entity.user.add_form';
        $route_parameters = [];
        // Check if user has access to create users.
        $access = $this->entityTypeManager->getAccessControlHandler('user')->createAccess(NULL, NULL, [], TRUE);
        $cache_tags[] = 'user_list';
        break;

      case 'taxonomy_term':
        $route_name = 'entity.taxonomy_term.add_form';
        $route_parameters = ['taxonomy_vocabulary' => $vocabulary];
        // Check if user has access to create terms in this vocabulary.
        $access = $this->entityTypeManager->getAccessControlHandler('taxonomy_term')->createAccess($vocabulary, NULL, [], TRUE);
        $cache_tags[] = "taxonomy_vocabulary:{$vocabulary}";
        break;
    }

    if (!empty($route_name)) {
      $url = Url::fromRoute($route_name, $route_parameters ?? []);
      $link_options = ['attributes' => ['class' => explode(' ', $css_classes)]];
      $url->setOptions($link_options);

      $link = Link::fromTextAndUrl($link_text, $url)->toRenderable();

      $link['#access'] = $access;
      $link['#cache'] = [
        'contexts' => [
          'user.permissions',
        ],
        'tags' => $cache_tags,
        'max-age' => Cache::PERMANENT,
      ];

      return $link;
    }

    // Return an empty render array if no route is defined.
    return ['#access' => FALSE];
  }

}

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

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