TermSelection.php 2.23 KB
Newer Older
1 2
<?php

3
namespace Drupal\taxonomy\Plugin\EntityReferenceSelection;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Core\Database\Query\SelectInterface;
7
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\taxonomy\Entity\Vocabulary;
10 11 12 13

/**
 * Provides specific access control for the taxonomy_term entity type.
 *
14
 * @EntityReferenceSelection(
15
 *   id = "default:taxonomy_term",
16 17 18 19 20 21
 *   label = @Translation("Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "default",
 *   weight = 1
 * )
 */
22
class TermSelection extends DefaultSelection {
23 24

  /**
25
   * {@inheritdoc}
26 27 28 29 30 31
   */
  public function entityQueryAlter(SelectInterface $query) {
    // @todo: How to set access, as vocabulary is now config?
  }

  /**
32
   * {@inheritdoc}
33
   */
34 35
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
36

37
    $form['target_bundles']['#title'] = $this->t('Available Vocabularies');
38 39 40 41 42

    // Sorting is not possible for taxonomy terms because we use
    // \Drupal\taxonomy\TermStorageInterface::loadTree() to retrieve matches.
    $form['sort']['#access'] = FALSE;

43 44 45 46 47
    return $form;

  }

  /**
48
   * {@inheritdoc}
49
   */
50
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
51
    if ($match || $limit) {
52
      return parent::getReferenceableEntities($match, $match_operator, $limit);
53 54 55 56
    }

    $options = array();

57 58
    $bundles = $this->entityManager->getBundleInfo('taxonomy_term');
    $handler_settings = $this->configuration['handler_settings'];
59
    $bundle_names = !empty($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : array_keys($bundles);
60 61

    foreach ($bundle_names as $bundle) {
62
      if ($vocabulary = Vocabulary::load($bundle)) {
63
        if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) {
64
          foreach ($terms as $term) {
65
            $options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . Html::escape($this->entityManager->getTranslationFromContext($term)->label());
66 67 68 69 70 71 72
          }
        }
      }
    }

    return $options;
  }
73

74
}