public function TermTest::testTaxonomyTermHierarchy in Drupal 9
Same name and namespace in other branches
- 8 core/modules/taxonomy/tests/src/Functional/TermTest.php \Drupal\Tests\taxonomy\Functional\TermTest::testTaxonomyTermHierarchy()
Tests terms in a single and multiple hierarchy.
File
- core/
modules/ taxonomy/ tests/ src/ Functional/ TermTest.php, line 96
Class
- TermTest
- Tests load, save and delete for taxonomy terms.
Namespace
Drupal\Tests\taxonomy\FunctionalCode
public function testTaxonomyTermHierarchy() {
// Create two taxonomy terms.
$term1 = $this
->createTerm($this->vocabulary);
$term2 = $this
->createTerm($this->vocabulary);
// Get the taxonomy storage.
/** @var \Drupal\taxonomy\TermStorageInterface $taxonomy_storage */
$taxonomy_storage = $this->container
->get('entity_type.manager')
->getStorage('taxonomy_term');
// Check that hierarchy is flat.
$this
->assertEquals(0, $taxonomy_storage
->getVocabularyHierarchyType($this->vocabulary
->id()), 'Vocabulary is flat.');
// Edit $term2, setting $term1 as parent.
$edit = [];
$edit['parent[]'] = [
$term1
->id(),
];
$this
->drupalGet('taxonomy/term/' . $term2
->id() . '/edit');
$this
->submitForm($edit, 'Save');
// Check the hierarchy.
$children = $taxonomy_storage
->loadChildren($term1
->id());
$parents = $taxonomy_storage
->loadParents($term2
->id());
$this
->assertTrue(isset($children[$term2
->id()]), 'Child found correctly.');
$this
->assertTrue(isset($parents[$term1
->id()]), 'Parent found correctly.');
// Load and save a term, confirming that parents are still set.
$term = Term::load($term2
->id());
$term
->save();
$parents = $taxonomy_storage
->loadParents($term2
->id());
$this
->assertTrue(isset($parents[$term1
->id()]), 'Parent found correctly.');
// Create a third term and save this as a parent of term2.
$term3 = $this
->createTerm($this->vocabulary);
$term2->parent = [
$term1
->id(),
$term3
->id(),
];
$term2
->save();
$parents = $taxonomy_storage
->loadParents($term2
->id());
$this
->assertArrayHasKey($term1
->id(), $parents);
$this
->assertArrayHasKey($term3
->id(), $parents);
}