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

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

5
use Drupal\Core\Entity\Element\EntityAutocomplete;
6
use Drupal\Core\Form\FormStateInterface;
7
use Drupal\taxonomy\Entity\Term;
8
9
use Drupal\taxonomy\TermStorageInterface;
use Drupal\taxonomy\VocabularyStorageInterface;
10
use Drupal\views\ViewExecutable;
11
use Drupal\views\Plugin\views\display\DisplayPluginBase;
12
use Drupal\views\Plugin\views\filter\ManyToOne;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14

15
16
17
18
/**
 * Filter by term id.
 *
 * @ingroup views_filter_handlers
19
 *
20
 * @ViewsFilter("taxonomy_index_tid")
21
22
 */
class TaxonomyIndexTid extends ManyToOne {
23

24
  // Stores the exposed input for this filter.
alexpott's avatar
alexpott committed
25
  public $validated_exposed_input = NULL;
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
57
58
59
60
61
62
63
64
65
66
67
68
  /**
   * 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,
69
70
      $container->get('entity_type.manager')->getStorage('taxonomy_vocabulary'),
      $container->get('entity_type.manager')->getStorage('taxonomy_term')
71
72
73
    );
  }

74
  /**
75
   * {@inheritdoc}
76
77
78
79
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

80
    if (!empty($this->definition['vocabulary'])) {
81
      $this->options['vid'] = $this->definition['vocabulary'];
82
83
84
    }
  }

85
86
87
  public function hasExtraOptions() {
    return TRUE;
  }
88

89
90
91
92
93
94
  /**
   * {@inheritdoc}
   */
  public function getValueOptions() {
    return $this->valueOptions;
  }
95

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

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

    return $options;
  }

108
  public function buildExtraOptionsForm(&$form, FormStateInterface $form_state) {
109
    $vocabularies = $this->vocabularyStorage->loadMultiple();
110
    $options = [];
111
    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'] = [
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
    $form['type'] = [
134
      '#type' => 'radios',
135
      '#title' => $this->t('Selection type'),
136
      '#options' => ['select' => $this->t('Dropdown'), 'textfield' => $this->t('Autocomplete')],
137
      '#default_value' => $this->options['type'],
138
    ];
139

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

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

    if ($this->options['type'] == 'textfield') {
162
163
164
      $terms = $this->value ? Term::loadMultiple(($this->value)) : [];
      $form['value'] = [
        '#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', ['@voc' => $vocabulary->label()]) : $this->t('Select terms'),
165
        '#type' => 'textfield',
166
        '#default_value' => EntityAutocomplete::getEntityLabels($terms),
167
      ];
168
169

      if ($this->options['limit']) {
170
171
        $form['value']['#type'] = 'entity_autocomplete';
        $form['value']['#target_type'] = 'taxonomy_term';
172
        $form['value']['#selection_settings']['target_bundles'] = [$vocabulary->id()];
173
174
        $form['value']['#tags'] = TRUE;
        $form['value']['#process_default_value'] = FALSE;
175
176
177
178
      }
    }
    else {
      if (!empty($this->options['hierarchy']) && $this->options['limit']) {
179
        $tree = $this->termStorage->loadTree($vocabulary->id(), 0, NULL, TRUE);
180
        $options = [];
181
182

        if ($tree) {
183
          foreach ($tree as $term) {
184
185
186
            if (!$term->isPublished()) {
              continue;
            }
187
            $choice = new \stdClass();
188
            $choice->option = [$term->id() => str_repeat('-', $term->depth) . \Drupal::service('entity.repository')->getTranslationFromContext($term)->label()];
189
190
191
192
193
            $options[] = $choice;
          }
        }
      }
      else {
194
        $options = [];
195
        $query = \Drupal::entityQuery('taxonomy_term')
196
          ->condition('status', 1)
197
198
          // @todo Sorting on vocabulary properties -
          //   https://www.drupal.org/node/1821274.
199
200
          ->sort('weight')
          ->sort('name')
201
          ->addTag('taxonomy_term_access');
202
        if ($this->options['limit']) {
203
          $query->condition('vid', $vocabulary->id());
204
        }
205
206
        $terms = Term::loadMultiple($query->execute());
        foreach ($terms as $term) {
207
          $options[$term->id()] = \Drupal::service('entity.repository')->getTranslationFromContext($term)->label();
208
209
210
211
212
        }
      }

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

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

        if (!empty($this->options['expose']['reduce'])) {
217
          $options = $this->reduceValueOptions($options);
218
219

          if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) {
220
            $default_value = [];
221
222
223
224
225
226
227
228
229
230
231
232
233
          }
        }

        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.
234
          elseif ($default_value == ['']) {
235
236
237
238
239
240
241
242
            $default_value = 'All';
          }
          else {
            $copy = $default_value;
            $default_value = array_shift($copy);
          }
        }
      }
243
      $form['value'] = [
244
        '#type' => 'select',
245
        '#title' => $this->options['limit'] ? $this->t('Select terms from vocabulary @voc', ['@voc' => $vocabulary->label()]) : $this->t('Select terms'),
246
247
248
249
        '#multiple' => TRUE,
        '#options' => $options,
        '#size' => min(9, count($options)),
        '#default_value' => $default_value,
250
      ];
251

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

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

      // Show help text if not exposed to end users.
      $form['value']['#description'] = t('Leave blank for all. Otherwise, the first selected term will be the default instead of "Any".');
265
266
267
    }
  }

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

274
275
    $tids = [];
    if ($values = $form_state->getValue(['options', 'value'])) {
276
277
278
      foreach ($values as $value) {
        $tids[] = $value['target_id'];
      }
279
    }
280
    $form_state->setValue(['options', 'value'], $tids);
281
282
  }

283
  public function acceptExposedInput($input) {
284
285
286
    if (empty($this->options['exposed'])) {
      return TRUE;
    }
287
288
289
290
291
292
    // We need to know the operator, which is normally set in
    // \Drupal\views\Plugin\views\filter\FilterPluginBase::acceptExposedInput(),
    // before we actually call the parent version of ourselves.
    if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) {
      $this->operator = $input[$this->options['expose']['operator_id']];
    }
293
294
295

    // If view is an attachment and is inheriting exposed filters, then assume
    // exposed input has already been validated
296
    if (!empty($this->view->is_attachment) && $this->view->display_handler->usesExposed()) {
297
298
299
      $this->validated_exposed_input = (array) $this->view->exposed_raw_input[$this->options['expose']['identifier']];
    }

300
301
302
303
304
305
    // If we're checking for EMPTY or NOT, we don't need any input, and we can
    // say that our input conditions are met by just having the right operator.
    if ($this->operator == 'empty' || $this->operator == 'not empty') {
      return TRUE;
    }

306
307
308
309
310
    // 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;
    }

311
    $rc = parent::acceptExposedInput($input);
312
313
314
315
316
317
318
319
320
321
    if ($rc) {
      // If we have previously validated input, override.
      if (isset($this->validated_exposed_input)) {
        $this->value = $this->validated_exposed_input;
      }
    }

    return $rc;
  }

322
  public function validateExposed(&$form, FormStateInterface $form_state) {
323
324
325
326
327
328
329
330
    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') {
331
      if ($form_state->getValue($identifier) != 'All') {
332
        $this->validated_exposed_input = (array) $form_state->getValue($identifier);
333
334
335
336
337
338
339
340
      }
      return;
    }

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

341
342
343
344
    if ($values = $form_state->getValue($identifier)) {
      foreach ($values as $value) {
        $this->validated_exposed_input[] = $value['target_id'];
      }
345
346
347
    }
  }

348
  protected function valueSubmit($form, FormStateInterface $form_state) {
349
350
351
    // prevent array_filter from messing up our arrays in parent submit.
  }

352
  public function buildExposeForm(&$form, FormStateInterface $form_state) {
353
    parent::buildExposeForm($form, $form_state);
354
355
356
    if ($this->options['type'] != 'select') {
      unset($form['expose']['reduce']);
    }
357
    $form['error_message'] = [
358
      '#type' => 'checkbox',
359
      '#title' => $this->t('Display error message'),
360
      '#default_value' => !empty($this->options['error_message']),
361
    ];
362
363
  }

364
  public function adminSummary() {
365
    // set up $this->valueOptions for the parent summary
366
    $this->valueOptions = [];
367
368
369

    if ($this->value) {
      $this->value = array_filter($this->value);
370
371
      $terms = Term::loadMultiple($this->value);
      foreach ($terms as $term) {
372
        $this->valueOptions[$term->id()] = \Drupal::service('entity.repository')->getTranslationFromContext($term)->label();
373
374
      }
    }
375
    return parent::adminSummary();
376
  }
377

378
379
380
381
382
383
384
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $contexts = parent::getCacheContexts();
    // The result potentially depends on term access and so is just cacheable
    // per user.
385
    // @todo See https://www.drupal.org/node/2352175.
386
    $contexts[] = 'user';
387
388
389
390

    return $contexts;
  }

391
392
393
394
395
396
397
398
399
  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

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

400
    foreach ($this->termStorage->loadMultiple($this->options['value']) as $term) {
401
402
403
404
405
406
      $dependencies[$term->getConfigDependencyKey()][] = $term->getConfigDependencyName();
    }

    return $dependencies;
  }

407
}