TaxonomyIndexTid.php 14.5 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid.
6 7
 */

8
namespace Drupal\taxonomy\Plugin\views\filter;
9

10
use Drupal\Core\Entity\EntityManagerInterface;
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\taxonomy\Entity\Term;
13 14
use Drupal\taxonomy\TermStorageInterface;
use Drupal\taxonomy\VocabularyStorageInterface;
15
use Drupal\views\ViewExecutable;
16
use Drupal\views\Plugin\views\display\DisplayPluginBase;
17
use Drupal\views\Plugin\views\filter\ManyToOne;
18
use Drupal\Component\Utility\String;
19
use Drupal\Component\Utility\Tags;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21

22 23 24 25
/**
 * Filter by term id.
 *
 * @ingroup views_filter_handlers
26
 *
27
 * @ViewsFilter("taxonomy_index_tid")
28 29
 */
class TaxonomyIndexTid extends ManyToOne {
30

31 32 33
  // Stores the exposed input for this filter.
  var $validated_exposed_input = NULL;

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  /**
   * The vocabulary storage.
   *
   * @var \Drupal\taxonomy\VocabularyStorageInterface
   */
  protected $vocabularyStorage;

  /**
   * The term storage.
   *
   * @var \Drupal\taxonomy\TermStorageInterface
   */
  protected $termStorage;

  /**
   * 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.
   * @param \Drupal\taxonomy\TermStorageInterface $term_storage
   *   The term storage.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, VocabularyStorageInterface $vocabulary_storage, TermStorageInterface $term_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->vocabularyStorage = $vocabulary_storage;
    $this->termStorage = $term_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'),
      $container->get('entity.manager')->getStorage('taxonomy_term')
    );
  }

81 82 83 84 85 86
  /**
   * Overrides \Drupal\views\Plugin\views\filter\ManyToOne::init().
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

87
    if (!empty($this->definition['vocabulary'])) {
88
      $this->options['vid'] = $this->definition['vocabulary'];
89 90 91
    }
  }

92
  public function hasExtraOptions() { return TRUE; }
93

94
  public function getValueOptions() { /* don't overwrite the value options */ }
95

96 97
  protected function defineOptions() {
    $options = parent::defineOptions();
98 99

    $options['type'] = array('default' => 'textfield');
100
    $options['limit'] = array('default' => TRUE);
101
    $options['vid'] = array('default' => '');
102
    $options['hierarchy'] = array('default' => FALSE);
103
    $options['error_message'] = array('default' => TRUE);
104 105 106 107

    return $options;
  }

108
  public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) {
109
    $vocabularies = entity_load_multiple('taxonomy_vocabulary');
110 111
    $options = array();
    foreach ($vocabularies as $voc) {
112
      $options[$voc->id()] = $voc->label();
113 114 115 116
    }

    if ($this->options['limit']) {
      // We only do this when the form is displayed.
117
      if (empty($this->options['vid'])) {
118
        $first_vocabulary = reset($vocabularies);
119
        $this->options['vid'] = $first_vocabulary->id();
120 121 122
      }

      if (empty($this->definition['vocabulary'])) {
123
        $form['vid'] = array(
124
          '#type' => 'radios',
125
          '#title' => $this->t('Vocabulary'),
126
          '#options' => $options,
127
          '#description' => $this->t('Select which vocabulary to show terms for in the regular options.'),
128
          '#default_value' => $this->options['vid'],
129 130 131 132 133 134
        );
      }
    }

    $form['type'] = array(
      '#type' => 'radios',
135 136
      '#title' => $this->t('Selection type'),
      '#options' => array('select' => $this->t('Dropdown'), 'textfield' => $this->t('Autocomplete')),
137 138 139 140 141
      '#default_value' => $this->options['type'],
    );

    $form['hierarchy'] = array(
      '#type' => 'checkbox',
142
      '#title' => $this->t('Show hierarchy in dropdown'),
143 144 145 146 147 148 149 150 151
      '#default_value' => !empty($this->options['hierarchy']),
      '#states' => array(
        'visible' => array(
          ':input[name="options[type]"]' => array('value' => 'select'),
        ),
      ),
    );
  }

152
  protected function valueForm(&$form, FormStateInterface $form_state) {
153
    $vocabulary = entity_load('taxonomy_vocabulary', $this->options['vid']);
154 155
    if (empty($vocabulary) && $this->options['limit']) {
      $form['markup'] = array(
156
        '#markup' => '<div class="form-item">' . $this->t('An invalid vocabulary is selected. Please change it in the options.') . '</div>',
157 158 159 160 161 162 163
      );
      return;
    }

    if ($this->options['type'] == 'textfield') {
      $default = '';
      if ($this->value) {
164 165
        $terms = Term::loadMultiple(($this->value));
        foreach ($terms as $term) {
166 167 168
          if ($default) {
            $default .= ', ';
          }
169
          $default .= String::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label());
170 171 172 173
        }
      }

      $form['value'] = array(
174
        '#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())) : $this->t('Select terms'),
175 176 177 178 179
        '#type' => 'textfield',
        '#default_value' => $default,
      );

      if ($this->options['limit']) {
180
        $form['value']['#autocomplete_route_name'] = 'taxonomy.autocomplete_vid';
181
        $form['value']['#autocomplete_route_parameters'] = array('taxonomy_vocabulary' => $vocabulary->id());
182 183 184 185
      }
    }
    else {
      if (!empty($this->options['hierarchy']) && $this->options['limit']) {
186
        $tree = taxonomy_get_tree($vocabulary->id(), 0, NULL, TRUE);
187 188 189
        $options = array();

        if ($tree) {
190
          foreach ($tree as $term) {
191
            $choice = new \stdClass();
192
            $choice->option = array($term->id() => str_repeat('-', $term->depth) . String::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label()));
193 194 195 196 197 198
            $options[] = $choice;
          }
        }
      }
      else {
        $options = array();
199 200 201 202 203
        $query = \Drupal::entityQuery('taxonomy_term')
          // @todo Sorting on vocabulary properties http://drupal.org/node/1821274
          ->sort('weight')
          ->sort('name')
          ->addTag('term_access');
204
        if ($this->options['limit']) {
205
          $query->condition('vid', $vocabulary->id());
206
        }
207 208 209
        $terms = Term::loadMultiple($query->execute());
        foreach ($terms as $term) {
          $options[$term->id()] = String::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label());
210 211 212 213 214
        }
      }

      $default_value = (array) $this->value;

215
      if ($exposed = $form_state->get('exposed')) {
216 217 218
        $identifier = $this->options['expose']['identifier'];

        if (!empty($this->options['expose']['reduce'])) {
219
          $options = $this->reduceValueOptions($options);
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246

          if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) {
            $default_value = array();
          }
        }

        if (empty($this->options['expose']['multiple'])) {
          if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) {
            $default_value = 'All';
          }
          elseif (empty($default_value)) {
            $keys = array_keys($options);
            $default_value = array_shift($keys);
          }
          // Due to #1464174 there is a chance that array('') was saved in the admin ui.
          // Let's choose a safe default value.
          elseif ($default_value == array('')) {
            $default_value = 'All';
          }
          else {
            $copy = $default_value;
            $default_value = array_shift($copy);
          }
        }
      }
      $form['value'] = array(
        '#type' => 'select',
247
        '#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())) : $this->t('Select terms'),
248 249 250 251 252 253
        '#multiple' => TRUE,
        '#options' => $options,
        '#size' => min(9, count($options)),
        '#default_value' => $default_value,
      );

254
      $user_input = $form_state->getUserInput();
255
      if ($exposed && isset($identifier) && !isset($user_input[$identifier])) {
256 257
        $user_input[$identifier] = $default_value;
        $form_state->setUserInput($user_input);
258 259 260
      }
    }

261
    if (!$form_state->get('exposed')) {
262
      // Retain the helper option
263
      $this->helper->buildOptionsForm($form, $form_state);
264 265 266
    }
  }

267
  protected function valueValidate($form, FormStateInterface $form_state) {
268 269 270 271 272
    // We only validate if they've chosen the text field style.
    if ($this->options['type'] != 'textfield') {
      return;
    }

273 274 275
    $values = Tags::explode($form_state->getValue('options', 'value'));
    if ($tids = $this->validate_term_strings($form['value'], $values, $form_state)) {
      $form_state->setValue(array('options', 'value'), $tids);
276 277 278
    }
  }

279
  public function acceptExposedInput($input) {
280 281 282 283 284 285
    if (empty($this->options['exposed'])) {
      return TRUE;
    }

    // If view is an attachment and is inheriting exposed filters, then assume
    // exposed input has already been validated
286
    if (!empty($this->view->is_attachment) && $this->view->display_handler->usesExposed()) {
287 288 289 290 291 292 293 294
      $this->validated_exposed_input = (array) $this->view->exposed_raw_input[$this->options['expose']['identifier']];
    }

    // If it's non-required and there's no value don't bother filtering.
    if (!$this->options['expose']['required'] && empty($this->validated_exposed_input)) {
      return FALSE;
    }

295
    $rc = parent::acceptExposedInput($input);
296 297 298 299 300 301 302 303 304 305
    if ($rc) {
      // If we have previously validated input, override.
      if (isset($this->validated_exposed_input)) {
        $this->value = $this->validated_exposed_input;
      }
    }

    return $rc;
  }

306
  public function validateExposed(&$form, FormStateInterface $form_state) {
307 308 309 310 311 312 313 314
    if (empty($this->options['exposed'])) {
      return;
    }

    $identifier = $this->options['expose']['identifier'];

    // We only validate if they've chosen the text field style.
    if ($this->options['type'] != 'textfield') {
315 316
      if ($form_state->getValue($identifier) != 'All')  {
        $this->validated_exposed_input = (array) $form_state->getValue($identifier);
317 318 319 320 321 322 323 324
      }
      return;
    }

    if (empty($this->options['expose']['identifier'])) {
      return;
    }

325
    $values = Tags::explode($form_state->getValue($identifier));
326

327
    $tids = $this->validate_term_strings($form[$identifier], $values, $form_state);
328 329 330 331 332 333 334 335 336 337 338 339 340 341
    if ($tids) {
      $this->validated_exposed_input = $tids;
    }
  }

  /**
   * Validate the user string. Since this can come from either the form
   * or the exposed filter, this is abstracted out a bit so it can
   * handle the multiple input sources.
   *
   * @param $form
   *   The form which is used, either the views ui or the exposed filters.
   * @param $values
   *   The taxonomy names which will be converted to tids.
342 343
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
344 345 346 347
   *
   * @return array
   *   The taxonomy ids fo all validated terms.
   */
348
  function validate_term_strings(&$form, $values, FormStateInterface $form_state) {
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    if (empty($values)) {
      return array();
    }

    $tids = array();
    $names = array();
    $missing = array();
    foreach ($values as $value) {
      $missing[strtolower($value)] = TRUE;
      $names[] = $value;
    }

    if (!$names) {
      return FALSE;
    }

365 366 367 368 369 370 371 372
    $query = \Drupal::entityQuery('taxonomy_term')
      ->condition('name', $names)
      ->condition('vid', $this->options['vid'])
      ->addTag('term_access');
    $terms = Term::loadMultiple($query->execute());
    foreach ($terms as $term) {
      unset($missing[strtolower(\Drupal::entityManager()->getTranslationFromContext($term)->label())]);
      $tids[] = $term->id();
373 374 375
    }

    if ($missing && !empty($this->options['error_message'])) {
376
      $form_state->setError($form, $this->formatPlural(count($missing), 'Unable to find term: @terms', 'Unable to find terms: @terms', array('@terms' => implode(', ', array_keys($missing)))));
377 378 379 380 381 382 383 384
    }
    elseif ($missing && empty($this->options['error_message'])) {
      $tids = array(0);
    }

    return $tids;
  }

385
  protected function valueSubmit($form, FormStateInterface $form_state) {
386 387 388
    // prevent array_filter from messing up our arrays in parent submit.
  }

389
  public function buildExposeForm(&$form, FormStateInterface $form_state) {
390
    parent::buildExposeForm($form, $form_state);
391 392 393 394 395
    if ($this->options['type'] != 'select') {
      unset($form['expose']['reduce']);
    }
    $form['error_message'] = array(
      '#type' => 'checkbox',
396
      '#title' => $this->t('Display error message'),
397 398 399 400
      '#default_value' => !empty($this->options['error_message']),
    );
  }

401
  public function adminSummary() {
402 403
    // set up $this->valueOptions for the parent summary
    $this->valueOptions = array();
404 405 406

    if ($this->value) {
      $this->value = array_filter($this->value);
407 408
      $terms = Term::loadMultiple($this->value);
      foreach ($terms as $term) {
409
        $this->valueOptions[$term->id()] = String::checkPlain(\Drupal::entityManager()->getTranslationFromContext($term)->label());
410 411
      }
    }
412
    return parent::adminSummary();
413
  }
414

415 416 417 418 419 420 421 422 423 424 425 426 427
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $contexts = parent::getCacheContexts();
    // The result potentially depends on term access and so is just cacheable
    // per user.
    // @todo https://www.drupal.org/node/2352175
    $contexts[] = 'cache.context.user';

    return $contexts;
  }

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

    $vocabulary = $this->vocabularyStorage->load($this->options['vid']);
    $dependencies[$vocabulary->getConfigDependencyKey()][] = $vocabulary->getConfigDependencyName();

    foreach ($this->options['value'] as $tid) {
      $term = $this->termStorage->load($tid);
      $dependencies[$term->getConfigDependencyKey()][] = $term->getConfigDependencyName();
    }

    return $dependencies;
  }

445
}