TermSelection.php 2.63 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\taxonomy\Plugin\EntityReferenceSelection\TermSelection.
6 7
 */

8
namespace Drupal\taxonomy\Plugin\EntityReferenceSelection;
9

10
use Drupal\Component\Utility\Html;
11
use Drupal\Core\Database\Query\SelectInterface;
12
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
13
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\taxonomy\Entity\Vocabulary;
15 16 17 18

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

  /**
30
   * {@inheritdoc}
31 32 33 34 35 36
   */
  public function entityQueryAlter(SelectInterface $query) {
    // @todo: How to set access, as vocabulary is now config?
  }

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

42
    $form['target_bundles']['#title'] = $this->t('Vocabularies');
43 44 45
    // @todo: Currently allow auto-create only on taxonomy terms.
    $form['auto_create'] = array(
      '#type' => 'checkbox',
46 47
      '#title' => $this->t("Create referenced entities if they don't already exist"),
      '#default_value' => isset($this->configuration['handler_settings']['auto_create']) ? $this->configuration['handler_settings']['auto_create'] : FALSE,
48
    );
49 50 51 52 53

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

54 55 56 57 58
    return $form;

  }

  /**
59
   * {@inheritdoc}
60
   */
61
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
62
    if ($match || $limit) {
63
      return parent::getReferenceableEntities($match , $match_operator, $limit);
64 65 66 67
    }

    $options = array();

68 69
    $bundles = $this->entityManager->getBundleInfo('taxonomy_term');
    $handler_settings = $this->configuration['handler_settings'];
70
    $bundle_names = !empty($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : array_keys($bundles);
71 72

    foreach ($bundle_names as $bundle) {
73
      if ($vocabulary = Vocabulary::load($bundle)) {
74
        if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) {
75
          foreach ($terms as $term) {
76
            $options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . Html::escape($term->getName());
77 78 79 80 81 82 83
          }
        }
      }
    }

    return $options;
  }
84

85
}