From e60979f1608932bb17bccecd07fbdfa49c94d0be Mon Sep 17 00:00:00 2001
From: Nathaniel Catchpole <catch@35733.no-reply.drupal.org>
Date: Tue, 19 Jun 2018 11:44:01 +0100
Subject: [PATCH] Issue #2977882 by Wim Leers: Term entity type's "parent"
 field does not specify "target_bundles" setting: a term from *any* vocabulary
 can be chosen

---
 core/modules/taxonomy/src/Entity/Term.php    | 10 ++++++++++
 core/modules/taxonomy/src/Tests/TermTest.php |  9 +++++++++
 2 files changed, 19 insertions(+)

diff --git a/core/modules/taxonomy/src/Entity/Term.php b/core/modules/taxonomy/src/Entity/Term.php
index 51e295a5177f..77cefcc0dca2 100644
--- a/core/modules/taxonomy/src/Entity/Term.php
+++ b/core/modules/taxonomy/src/Entity/Term.php
@@ -176,6 +176,16 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
     return $fields;
   }
 
+  /**
+   * {@inheritdoc}
+   */
+  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
+    // Only terms in the same bundle can be a parent.
+    $fields['parent'] = clone $base_field_definitions['parent'];
+    $fields['parent']->setSetting('handler_settings', ['target_bundles' => [$bundle => $bundle]]);
+    return $fields;
+  }
+
   /**
    * {@inheritdoc}
    */
diff --git a/core/modules/taxonomy/src/Tests/TermTest.php b/core/modules/taxonomy/src/Tests/TermTest.php
index abcde83d3301..54309c4237e2 100644
--- a/core/modules/taxonomy/src/Tests/TermTest.php
+++ b/core/modules/taxonomy/src/Tests/TermTest.php
@@ -72,6 +72,15 @@ protected function setUp() {
       ->save();
   }
 
+  /**
+   * The "parent" field must restrict references to the same vocabulary.
+   */
+  public function testParentHandlerSettings() {
+    $vocabulary_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('taxonomy_term', $this->vocabulary->id());
+    $parent_target_bundles = $vocabulary_fields['parent']->getSetting('handler_settings')['target_bundles'];
+    $this->assertIdentical([$this->vocabulary->id() => $this->vocabulary->id()], $parent_target_bundles);
+  }
+
   /**
    * Test terms in a single and multiple hierarchy.
    */
-- 
GitLab