TermSelection.php 2.28 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\taxonomy\Plugin\entity_reference\selection\TermSelection.
 */

namespace Drupal\taxonomy\Plugin\entity_reference\selection;

10
use Drupal\Component\Annotation\Plugin;
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Database\Query\SelectInterface;
use Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase;

/**
 * Provides specific access control for the taxonomy_term entity type.
 *
 * @Plugin(
 *   id = "taxonomy_term_default",
 *   module = "taxonomy",
 *   label = @Translation("Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "default",
 *   weight = 1
 * )
 */
class TermSelection extends SelectionBase {

  /**
   * Overrides SelectionBase::entityQueryAlter().
   */
  public function entityQueryAlter(SelectInterface $query) {
    // @todo: How to set access, as vocabulary is now config?
  }

  /**
   * Overrides SelectionBase::settingsForm().
   */
  public static function settingsForm(&$field, &$instance) {
    $form = parent::settingsForm($field, $instance);

    // @todo: Currently allow auto-create only on taxonomy terms.
    $form['auto_create'] = array(
      '#type' => 'checkbox',
      '#title' => t("Create referenced entities if they don't already exist"),
      '#default_value' => $instance['settings']['handler_settings']['auto_create'],
    );
    return $form;

  }


  /**
54
   * Overrides SelectionBase::getReferenceableEntities().
55
   */
56
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
57
    if ($match || $limit) {
58
      return parent::getReferenceableEntities($match , $match_operator, $limit);
59 60 61 62 63 64 65 66 67 68 69
    }

    $options = array();

    $bundles = entity_get_bundles('taxonomy_term');
    $bundle_names = !empty($this->instance['settings']['handler_settings']['target_bundles']) ? $this->instance['settings']['handler_settings']['target_bundles'] : array_keys($bundles);

    foreach ($bundle_names as $bundle) {
      if ($vocabulary = entity_load('taxonomy_vocabulary', $bundle)) {
        if ($terms = taxonomy_get_tree($vocabulary->id(), 0)) {
          foreach ($terms as $term) {
70
            $options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . check_plain($term->name);
71 72 73 74 75 76 77 78
          }
        }
      }
    }

    return $options;
  }
}