TaxonomyIndexTid.php 5.64 KB
Newer Older
1 2
<?php

3
namespace Drupal\taxonomy\Plugin\views\field;
4

5
use Drupal\Core\Form\FormStateInterface;
6
use Drupal\views\ViewExecutable;
7
use Drupal\views\Plugin\views\display\DisplayPluginBase;
8
use Drupal\views\Plugin\views\field\PrerenderList;
9 10
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\taxonomy\VocabularyStorageInterface;
11

12 13 14 15
/**
 * Field handler to display all taxonomy terms of a node.
 *
 * @ingroup views_field_handlers
16
 *
17
 * @ViewsField("taxonomy_index_tid")
18 19
 */
class TaxonomyIndexTid extends PrerenderList {
20

21 22 23
  /**
   * The vocabulary storage.
   *
24
   * @var \Drupal\taxonomy\VocabularyStorageInterface
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
   */
  protected $vocabularyStorage;

  /**
   * Constructs a TaxonomyIndexTid 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\taxonomy\VocabularyStorageInterface $vocabulary_storage
   *   The vocabulary storage.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, VocabularyStorageInterface $vocabulary_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->vocabularyStorage = $vocabulary_storage;
  }

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

57
  /**
58
   * {@inheritdoc}
59 60 61 62
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

63
    // @todo: Wouldn't it be possible to use $this->base_table and no if here?
64
    if ($view->storage->get('base_table') == 'node_field_revision') {
65
      $this->additional_fields['nid'] = ['table' => 'node_field_revision', 'field' => 'nid'];
66 67
    }
    else {
68
      $this->additional_fields['nid'] = ['table' => 'node_field_data', 'field' => 'nid'];
69 70 71
    }
  }

72 73
  protected function defineOptions() {
    $options = parent::defineOptions();
74

75 76 77
    $options['link_to_taxonomy'] = ['default' => TRUE];
    $options['limit'] = ['default' => FALSE];
    $options['vids'] = ['default' => []];
78 79 80 81 82 83 84

    return $options;
  }

  /**
   * Provide "link to term" option.
   */
85
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
86
    $form['link_to_taxonomy'] = [
87
      '#title' => $this->t('Link this field to its term page'),
88 89
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['link_to_taxonomy']),
90
    ];
91

92
    $form['limit'] = [
93
      '#type' => 'checkbox',
94
      '#title' => $this->t('Limit terms by vocabulary'),
dawehner's avatar
dawehner committed
95
      '#default_value' => $this->options['limit'],
96
    ];
97

98
    $options = [];
99
    $vocabularies = $this->vocabularyStorage->loadMultiple();
100
    foreach ($vocabularies as $voc) {
101
      $options[$voc->id()] = $voc->label();
102 103
    }

104
    $form['vids'] = [
105
      '#type' => 'checkboxes',
106
      '#title' => $this->t('Vocabularies'),
107
      '#options' => $options,
108
      '#default_value' => $this->options['vids'],
109 110 111 112 113
      '#states' => [
        'visible' => [
          ':input[name="options[limit]"]' => ['checked' => TRUE],
        ],
      ],
114

115
    ];
116

117
    parent::buildOptionsForm($form, $form_state);
118 119 120 121 122
  }

  /**
   * Add this term to the query
   */
123
  public function query() {
124
    $this->addAdditionalFields();
125 126
  }

127
  public function preRender(&$values) {
128
    $vocabularies = $this->vocabularyStorage->loadMultiple();
129
    $this->field_alias = $this->aliases['nid'];
130
    $nids = [];
131 132 133 134 135 136 137
    foreach ($values as $result) {
      if (!empty($result->{$this->aliases['nid']})) {
        $nids[] = $result->{$this->aliases['nid']};
      }
    }

    if ($nids) {
138
      $vocabs = array_filter($this->options['vids']);
139
      if (empty($this->options['limit'])) {
140
        $vocabs = [];
141
      }
142 143 144 145 146 147
      $result = \Drupal::entityManager()->getStorage('taxonomy_term')->getNodeTerms($nids, $vocabs);

      foreach ($result as $node_nid => $data) {
        foreach ($data as $tid => $term) {
          $this->items[$node_nid][$tid]['name'] = \Drupal::entityManager()->getTranslationFromContext($term)->label();
          $this->items[$node_nid][$tid]['tid'] = $tid;
148 149
          $this->items[$node_nid][$tid]['vocabulary_vid'] = $term->bundle();
          $this->items[$node_nid][$tid]['vocabulary'] = $vocabularies[$term->bundle()]->label();
150 151 152 153 154

          if (!empty($this->options['link_to_taxonomy'])) {
            $this->items[$node_nid][$tid]['make_link'] = TRUE;
            $this->items[$node_nid][$tid]['path'] = 'taxonomy/term/' . $tid;
          }
155 156 157 158 159
        }
      }
    }
  }

160
  public function render_item($count, $item) {
161 162 163
    return $item['name'];
  }

164
  protected function documentSelfTokens(&$tokens) {
165 166 167 168
    $tokens['{{ ' . $this->options['id'] . '__tid' . ' }}'] = $this->t('The taxonomy term ID for the term.');
    $tokens['{{ ' . $this->options['id'] . '__name' . ' }}'] = $this->t('The taxonomy term name for the term.');
    $tokens['{{ ' . $this->options['id'] . '__vocabulary_vid' . ' }}'] = $this->t('The machine name for the vocabulary the term belongs to.');
    $tokens['{{ ' . $this->options['id'] . '__vocabulary' . ' }}'] = $this->t('The name for the vocabulary the term belongs to.');
169 170
  }

171
  protected function addSelfTokens(&$tokens, $item) {
172
    foreach (['tid', 'name', 'vocabulary_vid', 'vocabulary'] as $token) {
173
      $tokens['{{ ' . $this->options['id'] . '__' . $token . ' }}'] = isset($item[$token]) ? $item[$token] : '';
174 175
    }
  }
176

177
}