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

3
namespace Drupal\taxonomy\Plugin\EntityReferenceSelection;
4

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

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

  /**
24
   * {@inheritdoc}
25
   */
26 27 28 29 30 31 32
  public function defaultConfiguration() {
    return [
      'sort' => [
        'field' => 'name',
        'direction' => 'asc',
      ]
    ] + parent::defaultConfiguration();
33 34 35
  }

  /**
36
   * {@inheritdoc}
37
   */
38 39
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
40

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

45 46 47 48 49
    return $form;

  }

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

57
    $options = [];
58

59
    $bundles = $this->entityManager->getBundleInfo('taxonomy_term');
60
    $bundle_names = $this->getConfiguration()['target_bundles'] ?: array_keys($bundles);
61 62

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

    return $options;
  }
74

75
}