/** * Tests using entity fields of the taxonomy term reference field type. */ public function testTaxonomyTermReferenceItem() { $tid = $this->term->id(); // Just being able to create the entity like this verifies a lot of code. $entity = entity_create('entity_test'); $entity->field_test_taxonomy->target_id = $this->term->id(); $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = entity_load('entity_test', $entity->id()); $this->assertTrue($entity->field_test_taxonomy instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_test_taxonomy[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_test_taxonomy->target_id, $this->term->id(), 'Field item contains the expected TID.'); $this->assertEqual($entity->field_test_taxonomy->entity->getName(), $this->term->getName(), 'Field item entity contains the expected name.'); $this->assertEqual($entity->field_test_taxonomy->entity->id(), $tid, 'Field item entity contains the expected ID.'); $this->assertEqual($entity->field_test_taxonomy->entity->uuid(), $this->term->uuid(), 'Field item entity contains the expected UUID.'); // Change the name of the term via the reference. $new_name = $this->randomMachineName(); $entity->field_test_taxonomy->entity->setName($new_name); $entity->field_test_taxonomy->entity->save(); // Verify it is the correct name. $term = Term::load($tid); $this->assertEqual($term->getName(), $new_name, 'The name of the term was changed.'); // Make sure the computed term reflects updates to the term id. $term2 = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'vid' => $this->term->getVocabularyId(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $term2->save(); $entity->field_test_taxonomy->target_id = $term2->id(); $this->assertEqual($entity->field_test_taxonomy->entity->id(), $term2->id(), 'Field item entity contains the new TID.'); $this->assertEqual($entity->field_test_taxonomy->entity->getName(), $term2->getName(), 'Field item entity contains the new name.'); // Test sample item generation. $entity = entity_create('entity_test'); $entity->field_test_taxonomy->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * Tests rolling back configuration and content entities. */ public function testRollback() { // We use vocabularies to demonstrate importing and rolling back // configuration entities. $vocabulary_data_rows = [['id' => '1', 'name' => 'categories', 'weight' => '2'], ['id' => '2', 'name' => 'tags', 'weight' => '1']]; $ids = ['id' => ['type' => 'integer']]; $config = ['id' => 'vocabularies', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $vocabulary_data_rows, 'ids' => $ids], 'process' => ['vid' => 'id', 'name' => 'name', 'weight' => 'weight'], 'destination' => ['plugin' => 'entity:taxonomy_vocabulary']]; $vocabulary_migration = Migration::create($config); $vocabulary_id_map = $vocabulary_migration->getIdMap(); $this->assertTrue($vocabulary_migration->getDestinationPlugin()->supportsRollback()); // Import and validate vocabulary config entities were created. $vocabulary_executable = new MigrateExecutable($vocabulary_migration, $this); $vocabulary_executable->import(); foreach ($vocabulary_data_rows as $row) { /** @var Vocabulary $vocabulary */ $vocabulary = Vocabulary::load($row['id']); $this->assertTrue($vocabulary); $map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]); $this->assertNotNull($map_row['destid1']); } // We use taxonomy terms to demonstrate importing and rolling back // content entities. $term_data_rows = [['id' => '1', 'vocab' => '1', 'name' => 'music'], ['id' => '2', 'vocab' => '2', 'name' => 'Bach'], ['id' => '3', 'vocab' => '2', 'name' => 'Beethoven']]; $ids = ['id' => ['type' => 'integer']]; $config = ['id' => 'terms', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $term_data_rows, 'ids' => $ids], 'process' => ['tid' => 'id', 'vid' => 'vocab', 'name' => 'name'], 'destination' => ['plugin' => 'entity:taxonomy_term'], 'migration_dependencies' => ['required' => ['vocabularies']]]; $term_migration = Migration::create($config); $term_id_map = $term_migration->getIdMap(); $this->assertTrue($term_migration->getDestinationPlugin()->supportsRollback()); // Import and validate term entities were created. $term_executable = new MigrateExecutable($term_migration, $this); $term_executable->import(); foreach ($term_data_rows as $row) { /** @var Term $term */ $term = Term::load($row['id']); $this->assertTrue($term); $map_row = $term_id_map->getRowBySource(['id' => $row['id']]); $this->assertNotNull($map_row['destid1']); } // Rollback and verify the entities are gone. $term_executable->rollback(); foreach ($term_data_rows as $row) { $term = Term::load($row['id']); $this->assertNull($term); $map_row = $term_id_map->getRowBySource(['id' => $row['id']]); $this->assertFalse($map_row); } $vocabulary_executable->rollback(); foreach ($vocabulary_data_rows as $row) { $term = Vocabulary::load($row['id']); $this->assertNull($term); $map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]); $this->assertFalse($map_row); } // Test that simple configuration is not rollbackable. $term_setting_rows = [['id' => 1, 'override_selector' => '0', 'terms_per_page_admin' => '10']]; $ids = ['id' => ['type' => 'integer']]; $config = ['id' => 'taxonomy_settings', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $term_setting_rows, 'ids' => $ids], 'process' => ['override_selector' => 'override_selector', 'terms_per_page_admin' => 'terms_per_page_admin'], 'destination' => ['plugin' => 'config', 'config_name' => 'taxonomy.settings'], 'migration_dependencies' => ['required' => ['vocabularies']]]; $settings_migration = Migration::create($config); $this->assertFalse($settings_migration->getDestinationPlugin()->supportsRollback()); }
/** * Tests creation of stubs when weight is mapped. */ public function testStubWithWeightMapping() { // Create a vocabulary via migration for the terms to reference. $vocabulary_data_rows = [['id' => '1', 'name' => 'tags']]; $ids = ['id' => ['type' => 'integer']]; $config = ['id' => 'vocabularies', 'migration_tags' => ['Stub test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $vocabulary_data_rows, 'ids' => $ids], 'process' => ['vid' => 'id', 'name' => 'name'], 'destination' => ['plugin' => 'entity:taxonomy_vocabulary']]; $vocabulary_migration = Migration::create($config); $vocabulary_executable = new MigrateExecutable($vocabulary_migration, $this); $vocabulary_executable->import(); // We have a term referencing an unmigrated parent, forcing a stub to be // created. $term_data_rows = [['id' => '1', 'vocab' => '1', 'name' => 'music', 'parent' => '2']]; $ids = ['id' => ['type' => 'integer']]; $config = ['id' => 'terms', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $term_data_rows, 'ids' => $ids], 'process' => ['tid' => 'id', 'vid' => 'vocab', 'name' => 'name', 'weight' => 'weight', 'parent' => ['plugin' => 'migration', 'migration' => 'terms', 'source' => 'parent']], 'destination' => ['plugin' => 'entity:taxonomy_term'], 'migration_dependencies' => ['required' => ['vocabularies']]]; $term_migration = Migration::create($config); $term_migration->save(); $term_executable = new MigrateExecutable($term_migration, $this); $term_executable->import(); // Load the referenced term, which should exist as a stub. /** @var \Drupal\Core\Entity\ContentEntityBase $stub_entity */ $stub_entity = Term::load(2); $this->assertTrue($stub_entity, 'Stub successfully created'); if ($stub_entity) { $this->assertIdentical(count($stub_entity->validate()), 0, 'Stub is a valid entity'); } }
/** * @return Drupal\taxonomy\Entity\Term|null */ private static function getTempStoreCarburant() { $temp_store = \Drupal::getContainer()->get('user.private_tempstore')->get(); $id = $temp_store->get('tip_carburant'); if ($id) { return Term::load($id); } }
/** * Tests the entity reference field type for referencing content entities. */ public function testContentEntityReferenceItem() { $tid = $this->term->id(); // Just being able to create the entity like this verifies a lot of code. $entity = entity_create('entity_test'); $entity->field_test_taxonomy_term->target_id = $tid; $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = entity_load('entity_test', $entity->id()); $this->assertTrue($entity->field_test_taxonomy_term instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_test_taxonomy_term[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_test_taxonomy_term->target_id, $tid); $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $this->term->getName()); $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $tid); $this->assertEqual($entity->field_test_taxonomy_term->entity->uuid(), $this->term->uuid()); // Change the name of the term via the reference. $new_name = $this->randomMachineName(); $entity->field_test_taxonomy_term->entity->setName($new_name); $entity->field_test_taxonomy_term->entity->save(); // Verify it is the correct name. $term = Term::load($tid); $this->assertEqual($term->getName(), $new_name); // Make sure the computed term reflects updates to the term id. $term2 = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'vid' => $this->term->bundle(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $term2->save(); // Test all the possible ways of assigning a value. $entity->field_test_taxonomy_term->target_id = $term->id(); $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id()); $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName()); $entity->field_test_taxonomy_term = [['target_id' => $term2->id()]]; $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term2->id()); $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName()); // Test value assignment via the computed 'entity' property. $entity->field_test_taxonomy_term->entity = $term; $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term->id()); $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName()); $entity->field_test_taxonomy_term = [['entity' => $term2]]; $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term2->id()); $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName()); // Test assigning an invalid item throws an exception. try { $entity->field_test_taxonomy_term = ['target_id' => 'invalid', 'entity' => $term2]; $this->fail('Assigning an invalid item throws an exception.'); } catch (\InvalidArgumentException $e) { $this->pass('Assigning an invalid item throws an exception.'); } // Delete terms so we have nothing to reference and try again $term->delete(); $term2->delete(); $entity = entity_create('entity_test', array('name' => $this->randomMachineName())); $entity->save(); // Test the generateSampleValue() method. $entity = entity_create('entity_test'); $entity->field_test_taxonomy_term->generateSampleItems(); $entity->field_test_taxonomy_vocabulary->generateSampleItems(); $this->entityValidateAndSave($entity); }
/** * Validate a migrated term contains the expected values. * * @param $id * Entity ID to load and check. * @param $expected_label * The label the migrated entity should have. * @param $expected_vid * The parent vocabulary the migrated entity should have. * @param string $expected_description * The description the migrated entity should have. * @param int $expected_weight * The weight the migrated entity should have. * @param array $expected_parents * The parent terms the migrated entity should have. */ protected function assertEntity($id, $expected_label, $expected_vid, $expected_description = '', $expected_weight = 0, $expected_parents = []) { /** @var \Drupal\taxonomy\TermInterface $entity */ $entity = Term::load($id); $this->assertTrue($entity instanceof TermInterface); $this->assertIdentical($expected_label, $entity->label()); $this->assertIdentical($expected_vid, $entity->getVocabularyId()); $this->assertEqual($expected_description, $entity->getDescription()); $this->assertEqual($expected_weight, $entity->getWeight()); $this->assertIdentical($expected_parents, $this->getParentIDs($id)); }
/** * Tests setting bundles both in process and destination. */ public function testMixedBundles() { $term_data_rows = [['id' => 1, 'vocab' => 'categories', 'name' => 'Category 1'], ['id' => 2, 'name' => 'Tag 1']]; $ids = ['id' => ['type' => 'integer']]; $definition = ['id' => 'terms', 'migration_tags' => ['Bundle test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $term_data_rows, 'ids' => $ids], 'process' => ['tid' => 'id', 'vid' => 'vocab', 'name' => 'name'], 'destination' => ['plugin' => 'entity:taxonomy_term', 'default_bundle' => 'tags'], 'migration_dependencies' => []]; $term_migration = \Drupal::service('plugin.manager.migration')->createStubMigration($definition); // Import and validate the term entities were created with the correct bundle. $term_executable = new MigrateExecutable($term_migration, $this); $term_executable->import(); /** @var Term $term */ $term = Term::load(1); $this->assertEquals($term->bundle(), 'categories'); $term = Term::load(2); $this->assertEquals($term->bundle(), 'tags'); }
/** * {@inheritdoc} */ public function build(FacetInterface $facet, array $results) { $language_interface = \Drupal::languageManager()->getCurrentLanguage(); /** @var \Drupal\facets\Result\ResultInterface $result */ foreach ($results as &$result) { /** @var \Drupal\taxonomy\Entity\Term $term */ $term = Term::load($result->getRawValue()); if ($term->hasTranslation($language_interface->getId())) { $term_trans = $term->getTranslation($language_interface->getId()); $result->setDisplayValue($term_trans->getName()); } else { $result->setDisplayValue($term->getName()); } } return $results; }
/** * {@inheritdoc} */ public function title() { if (!empty($this->argument)) { $this->fillValue(); $terms = array(); foreach ($this->value as $tid) { $taxonomy_term = Term::load($tid); if ($taxonomy_term) { $terms[] = Html::escape($taxonomy_term->label()); } } return $terms ? implode(', ', $terms) : Html::escape($this->argument); } else { return Html::escape($this->argument); } }
/** * {@inheritdoc} */ public function title() { if (!empty($this->argument)) { $this->fillValue(); $terms = array(); foreach ($this->value as $tid) { $taxonomy_term = Term::load($tid); if ($taxonomy_term) { $terms[] = SafeMarkup::checkPlain($taxonomy_term->label()); } } return $terms ? implode(', ', $terms) : SafeMarkup::checkPlain($this->argument); } else { return SafeMarkup::checkPlain($this->argument); } }
/** * {@inheritdoc} */ public function build(RouteMatchInterface $route_match) { $breadcrumb = new Breadcrumb(); $node = $route_match->getParameter('node'); // Homepage link. $links[] = Link::createFromRoute($this->t('Home'), '<front>'); // First assigned tag. if (!empty($node->field_tags[0]->target_id)) { $tid = $node->field_tags[0]->target_id; $term_name = Term::load($tid)->get('name')->value; $links[] = Link::createFromRoute($term_name, 'entity.taxonomy_term.canonical', ['taxonomy_term' => $tid]); } // The node itself. $links[] = Link::fromTextAndUrl($node->getTitle(), Url::fromRoute('<current>')); $breadcrumb->addCacheContexts(['route']); return $breadcrumb->setLinks($links); }
public function migrateNcdTaxonomy($import) { $query = \Drupal::entityQuery('taxonomy_term')->condition('field_old_id', $import->tid); $newId = $query->execute(); if (!empty($newId)) { //load entity for update $targetEntity = Term::load(array_pop($newId)); } else { //create entity and save $targetEntity = Term::create(array('vid' => $import->vocabulary_machine_name, 'name' => $import->name)); } $targetEntity->name = $import->name; $targetEntity->description = $import->description ?? ''; $targetEntity->field_menu_image = $this->processFile($import->field_menu_image); $targetEntity->field_category_header = $import->field_category_header ?? ''; $targetEntity->field_old_id = $import->tid; $targetEntity->save(); }
/** * Deleting a parent of a term with multiple parents does not delete the term. */ public function testMultipleParentDelete() { $vocabulary = $this->createVocabulary(); $parent_term1 = $this->createTerm($vocabulary); $parent_term2 = $this->createTerm($vocabulary); $child_term = $this->createTerm($vocabulary); $child_term->parent = array($parent_term1->id(), $parent_term2->id()); $child_term->save(); $child_term_id = $child_term->id(); $parent_term1->delete(); $term_storage = $this->container->get('entity.manager')->getStorage('taxonomy_term'); $term_storage->resetCache(array($child_term_id)); $child_term = Term::load($child_term_id); $this->assertTrue(!empty($child_term), 'Child term is not deleted if only one of its parents is removed.'); $parent_term2->delete(); $term_storage->resetCache(array($child_term_id)); $child_term = Term::load($child_term_id); $this->assertTrue(empty($child_term), 'Child term is deleted if all of its parents are removed.'); }
/** * Tests exportContent(). */ public function testExportContent() { \Drupal::service('module_installer')->install(['taxonomy', 'default_content']); \Drupal::service('router.builder')->rebuild(); $this->defaultContentManager = \Drupal::service('default_content.manager'); $vocabulary = Vocabulary::create(['vid' => 'test']); $vocabulary->save(); $term = Term::create(['vid' => $vocabulary->id(), 'name' => 'test_name']); $term->save(); $term = Term::load($term->id()); /** @var \Symfony\Component\Serializer\Serializer $serializer */ $serializer = \Drupal::service('serializer'); \Drupal::service('rest.link_manager')->setLinkDomain(DefaultContentManager::LINK_DOMAIN); $expected = $serializer->serialize($term, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]); $exported = $this->defaultContentManager->exportContent('taxonomy_term', $term->id()); $exported_decoded = json_decode($exported); // Ensure the proper UUID is part of it. $this->assertEqual($exported_decoded->uuid[0]->value, $term->uuid()); $this->assertEqual($exported, $expected); }
/** * Tests creation of stubs when weight is mapped. */ public function testStubWithWeightMapping() { // Create a vocabulary via migration for the terms to reference. $vocabulary_data_rows = [['id' => '1', 'name' => 'tags']]; $ids = ['id' => ['type' => 'integer']]; $definition = ['migration_tags' => ['Stub test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $vocabulary_data_rows, 'ids' => $ids], 'process' => ['vid' => 'id', 'name' => 'name'], 'destination' => ['plugin' => 'entity:taxonomy_vocabulary']]; $vocabulary_migration = new Migration([], uniqid(), $definition); $vocabulary_executable = new MigrateExecutable($vocabulary_migration, $this); $vocabulary_executable->import(); // We have a term referencing an unmigrated parent, forcing a stub to be // created. $migration = $this->getMigration('taxonomy_term_stub_test'); $term_executable = new MigrateExecutable($migration, $this); $term_executable->import(); $this->assertTrue($migration->getIdMap()->getRowBySource(['2']), 'Stub row exists in the ID map table'); // Load the referenced term, which should exist as a stub. /** @var \Drupal\Core\Entity\ContentEntityBase $stub_entity */ $stub_entity = Term::load(2); $this->assertTrue($stub_entity, 'Stub successfully created'); if ($stub_entity) { $this->assertIdentical(count($stub_entity->validate()), 0, 'Stub is a valid entity'); } }
/** * Tests that many terms with parents show on each page */ function testTaxonomyTermChildTerms() { // Set limit to 10 terms per page. Set variable to 9 so 10 terms appear. \Drupal::config('taxonomy.settings')->set('terms_per_page_admin', '9')->save(); $term1 = $this->createTerm($this->vocabulary); $terms_array = ''; // Create 40 terms. Terms 1-12 get parent of $term1. All others are // individual terms. for ($x = 1; $x <= 40; $x++) { $edit = array(); // Set terms in order so we know which terms will be on which pages. $edit['weight'] = $x; // Set terms 1-20 to be children of first term created. if ($x <= 12) { $edit['parent'] = $term1->id(); } $term = $this->createTerm($this->vocabulary, $edit); $children = taxonomy_term_load_children($term1->id()); $parents = taxonomy_term_load_parents($term->id()); $terms_array[$x] = Term::load($term->id()); } // Get Page 1. $this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/overview'); $this->assertText($term1->getName(), 'Parent Term is displayed on Page 1'); for ($x = 1; $x <= 13; $x++) { $this->assertText($terms_array[$x]->getName(), $terms_array[$x]->getName() . ' found on Page 1'); } // Get Page 2. $this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/overview', array('query' => array('page' => 1))); $this->assertText($term1->getName(), 'Parent Term is displayed on Page 2'); for ($x = 1; $x <= 18; $x++) { $this->assertText($terms_array[$x]->getName(), $terms_array[$x]->getName() . ' found on Page 2'); } // Get Page 3. $this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/overview', array('query' => array('page' => 2))); $this->assertNoText($term1->getName(), 'Parent Term is not displayed on Page 3'); for ($x = 1; $x <= 17; $x++) { $this->assertNoText($terms_array[$x]->getName(), $terms_array[$x]->getName() . ' not found on Page 3'); } for ($x = 18; $x <= 25; $x++) { $this->assertText($terms_array[$x]->getName(), $terms_array[$x]->getName() . ' found on Page 3'); } }
/** * Tests rolling back configuration and content entities. */ public function testRollback() { // We use vocabularies to demonstrate importing and rolling back // configuration entities. $vocabulary_data_rows = [['id' => '1', 'name' => 'categories', 'weight' => '2'], ['id' => '2', 'name' => 'tags', 'weight' => '1']]; $ids = ['id' => ['type' => 'integer']]; $definition = ['id' => 'vocabularies', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $vocabulary_data_rows, 'ids' => $ids], 'process' => ['vid' => 'id', 'name' => 'name', 'weight' => 'weight'], 'destination' => ['plugin' => 'entity:taxonomy_vocabulary']]; $vocabulary_migration = new Migration([], uniqid(), $definition); $vocabulary_id_map = $vocabulary_migration->getIdMap(); $this->assertTrue($vocabulary_migration->getDestinationPlugin()->supportsRollback()); // Import and validate vocabulary config entities were created. $vocabulary_executable = new MigrateExecutable($vocabulary_migration, $this); $vocabulary_executable->import(); foreach ($vocabulary_data_rows as $row) { /** @var Vocabulary $vocabulary */ $vocabulary = Vocabulary::load($row['id']); $this->assertTrue($vocabulary); $map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]); $this->assertNotNull($map_row['destid1']); } // We use taxonomy terms to demonstrate importing and rolling back content // entities. $term_data_rows = [['id' => '1', 'vocab' => '1', 'name' => 'music'], ['id' => '2', 'vocab' => '2', 'name' => 'Bach'], ['id' => '3', 'vocab' => '2', 'name' => 'Beethoven']]; $ids = ['id' => ['type' => 'integer']]; $definition = ['id' => 'terms', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $term_data_rows, 'ids' => $ids], 'process' => ['tid' => 'id', 'vid' => 'vocab', 'name' => 'name'], 'destination' => ['plugin' => 'entity:taxonomy_term'], 'migration_dependencies' => ['required' => ['vocabularies']]]; $term_migration = new Migration([], uniqid(), $definition); $term_id_map = $term_migration->getIdMap(); $this->assertTrue($term_migration->getDestinationPlugin()->supportsRollback()); // Pre-create a term, to make sure it isn't deleted on rollback. $preserved_term_ids[] = 1; $new_term = Term::create(['tid' => 1, 'vid' => 1, 'name' => 'music']); $new_term->save(); // Import and validate term entities were created. $term_executable = new MigrateExecutable($term_migration, $this); $term_executable->import(); // Also explicitly mark one row to be preserved on rollback. $preserved_term_ids[] = 2; $map_row = $term_id_map->getRowBySource(['id' => 2]); $dummy_row = new Row(['id' => 2], $ids); $term_id_map->saveIdMapping($dummy_row, [$map_row['destid1']], $map_row['source_row_status'], MigrateIdMapInterface::ROLLBACK_PRESERVE); foreach ($term_data_rows as $row) { /** @var Term $term */ $term = Term::load($row['id']); $this->assertTrue($term); $map_row = $term_id_map->getRowBySource(['id' => $row['id']]); $this->assertNotNull($map_row['destid1']); } // Rollback and verify the entities are gone. $term_executable->rollback(); foreach ($term_data_rows as $row) { $term = Term::load($row['id']); if (in_array($row['id'], $preserved_term_ids)) { $this->assertNotNull($term); } else { $this->assertNull($term); } $map_row = $term_id_map->getRowBySource(['id' => $row['id']]); $this->assertFalse($map_row); } $vocabulary_executable->rollback(); foreach ($vocabulary_data_rows as $row) { $term = Vocabulary::load($row['id']); $this->assertNull($term); $map_row = $vocabulary_id_map->getRowBySource(['id' => $row['id']]); $this->assertFalse($map_row); } // Test that simple configuration is not rollbackable. $term_setting_rows = [['id' => 1, 'override_selector' => '0', 'terms_per_page_admin' => '10']]; $ids = ['id' => ['type' => 'integer']]; $definition = ['id' => 'taxonomy_settings', 'migration_tags' => ['Import and rollback test'], 'source' => ['plugin' => 'embedded_data', 'data_rows' => $term_setting_rows, 'ids' => $ids], 'process' => ['override_selector' => 'override_selector', 'terms_per_page_admin' => 'terms_per_page_admin'], 'destination' => ['plugin' => 'config', 'config_name' => 'taxonomy.settings'], 'migration_dependencies' => ['required' => ['vocabularies']]]; $settings_migration = new Migration([], uniqid(), $definition); $this->assertFalse($settings_migration->getDestinationPlugin()->supportsRollback()); }
/** * Function to display the faq page. * * @param int $tid * Default is 0, determines if the questions and answers on the page * will be shown according to a category or non-categorized. * @param string $faq_display * Optional parameter to override default question layout setting. * @param string $category_display * Optional parameter to override default category layout setting. * @return * The page with FAQ questions and answers. * @throws NotFoundHttpException */ public function faqPage($tid = 0, $faq_display = '', $category_display = '') { $faq_settings = \Drupal::config('faq.settings'); $output = $output_answers = ''; $build = array(); $build['#type'] = 'markup'; $build['#attached']['css'] = array(drupal_get_path('module', 'faq') . '/css/faq.css'); $build['#title'] = $faq_settings->get('title'); if (!$this->moduleHandler()->moduleExists('taxonomy')) { $tid = 0; } $faq_display = $faq_settings->get('display'); $use_categories = $faq_settings->get('use_categories'); $category_display = $faq_settings->get('category_display'); // if taxonomy doesn't installed, do not use categories if (!$this->moduleHandler()->moduleExists('taxonomy')) { $use_categories = FALSE; } if ($use_categories && $category_display == 'hide_qa' || $faq_display == 'hide_answer') { $build['#attached']['js'] = array(array('data' => drupal_get_path('module', 'faq') . '/js/faq.js'), array('data' => array('hide_qa_accordion' => $faq_settings->get('hide_qa_accordion'), 'category_hide_qa_accordion' => $faq_settings->get('category_hide_qa_accordion')), 'type' => 'setting')); } // Non-categorized questions and answers. if (!$use_categories || $category_display == 'none' && empty($tid)) { if (!empty($tid)) { throw new NotFoundHttpException(); } $default_sorting = $faq_settings->get('default_sorting'); $query = db_select('node', 'n'); $weight_alias = $query->leftJoin('faq_weights', 'w', '%alias.nid=n.nid'); $node_data = $query->leftJoin('node_field_data', 'd', 'd.nid=n.nid'); $query->addTag('node_access')->fields('n', array('nid'))->condition('n.type', 'faq')->condition('d.status', 1)->condition(db_or()->condition("{$weight_alias}.tid", 0)->isNull("{$weight_alias}.tid")); $default_weight = 0; if ($default_sorting == 'ASC') { $default_weight = 1000000; } // Works, but involves variable concatenation - safe though, since // $default_weight is an integer. $query->addExpression("COALESCE(w.weight, {$default_weight})", 'effective_weight'); // Doesn't work in Postgres. //$query->addExpression('COALESCE(w.weight, CAST(:default_weight as SIGNED))', 'effective_weight', array(':default_weight' => $default_weight)); $query->orderBy('effective_weight', 'ASC')->orderBy('d.sticky', 'DESC'); if ($default_sorting == 'ASC') { $query->orderBy('d.created', 'ASC'); } else { $query->orderBy('d.created', 'DESC'); } // Only need the nid column. $nids = $query->execute()->fetchCol(); $data = Node::loadMultiple($nids); $questions_to_render = array(); $questions_to_render['#data'] = $data; switch ($faq_display) { case 'questions_top': $questions_to_render['#theme'] = 'faq_questions_top'; break; case 'hide_answer': $questions_to_render['#theme'] = 'faq_hide_answer'; break; case 'questions_inline': $questions_to_render['#theme'] = 'faq_questions_inline'; break; case 'new_page': $questions_to_render['#theme'] = 'faq_new_page'; break; } // End of switch. $output = drupal_render($questions_to_render); } else { $hide_child_terms = $faq_settings->get('hide_child_terms'); // If we're viewing a specific category/term. if (!empty($tid)) { if ($term = Term::load($tid)) { $title = $faq_settings->get('title'); $build['#title'] = $title . ($title ? ' - ' : '') . $this->t($term->getName()); $this->_displayFaqByCategory($faq_display, $category_display, $term, 0, $output, $output_answers); $to_render = array('#theme' => 'faq_page', '#content' => SafeMarkup::set($output), '#answers' => SafeMarkup::set($output_answers)); $build['#markup'] = drupal_render($to_render); return $build; } else { throw new NotFoundHttpException(); } } $list_style = $faq_settings->get('category_listing'); $vocabularies = Vocabulary::loadMultiple(); $vocab_omit = $faq_settings->get('omit_vocabulary'); $items = array(); $vocab_items = array(); foreach ($vocabularies as $vid => $vobj) { if (isset($vocab_omit[$vid]) && $vocab_omit[$vid] != 0) { continue; } if ($category_display == "new_page") { $vocab_items = $this->_getIndentedFaqTerms($vid, 0); $items = array_merge($items, $vocab_items); } else { if ($hide_child_terms && $category_display == 'hide_qa') { $tree = taxonomy_get_tree($vid, 0, 1, TRUE); } else { $tree = taxonomy_get_tree($vid, 0, NULL, TRUE); } foreach ($tree as $term) { switch ($category_display) { case 'hide_qa': case 'categories_inline': if (FaqHelper::taxonomyTermCountNodes($term->id())) { $this->_displayFaqByCategory($faq_display, $category_display, $term, 1, $output, $output_answers); } break; } } } } if ($category_display == "new_page") { $output = $this->_renderCategoriesToList($items, $list_style); } } $faq_description = $faq_settings->get('description'); $markup = array('#theme' => 'faq_page', '#content' => SafeMarkup::set($output), '#answers' => SafeMarkup::set($output_answers), '#description' => SafeMarkup::set($faq_description)); $build['#markup'] = drupal_render($markup); return $build; }
/** * Tests hook invocations for CRUD operations on taxonomy terms. */ public function testTaxonomyTermHooks() { $this->installEntitySchema('taxonomy_term'); $vocabulary = entity_create('taxonomy_vocabulary', array('name' => 'Test vocabulary', 'vid' => 'test', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'description' => NULL, 'module' => 'entity_crud_hook_test')); $vocabulary->save(); $GLOBALS['entity_crud_hook_test'] = array(); $term = entity_create('taxonomy_term', array('vid' => $vocabulary->id(), 'name' => 'Test term', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'description' => NULL, 'format' => 1)); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_term_create called', 'entity_crud_hook_test_entity_create called for type taxonomy_term')); $GLOBALS['entity_crud_hook_test'] = array(); $term->save(); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_term_presave called', 'entity_crud_hook_test_entity_presave called for type taxonomy_term', 'entity_crud_hook_test_taxonomy_term_insert called', 'entity_crud_hook_test_entity_insert called for type taxonomy_term')); $GLOBALS['entity_crud_hook_test'] = array(); $term = Term::load($term->id()); $this->assertHookMessageOrder(array('entity_crud_hook_test_entity_load called for type taxonomy_term', 'entity_crud_hook_test_taxonomy_term_load called')); $GLOBALS['entity_crud_hook_test'] = array(); $term->setName('New name'); $term->save(); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_term_presave called', 'entity_crud_hook_test_entity_presave called for type taxonomy_term', 'entity_crud_hook_test_taxonomy_term_update called', 'entity_crud_hook_test_entity_update called for type taxonomy_term')); $GLOBALS['entity_crud_hook_test'] = array(); $term->delete(); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_term_predelete called', 'entity_crud_hook_test_entity_predelete called for type taxonomy_term', 'entity_crud_hook_test_taxonomy_term_delete called', 'entity_crud_hook_test_entity_delete called for type taxonomy_term')); }
/** * Tests the filter UI. */ public function testFilterUI() { $this->drupalGet('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid'); $result = $this->xpath('//select[@id="edit-options-value"]/option'); // Ensure that the expected hierarchy is available in the UI. $counter = 0; for ($i = 0; $i < 3; $i++) { for ($j = 0; $j <= $i; $j++) { $option = $result[$counter++]; $prefix = $this->terms[$i][$j]->parent->target_id ? '-' : ''; $attributes = $option->attributes(); $tid = (string) $attributes->value; $this->assertEqual($prefix . $this->terms[$i][$j]->getName(), (string) $option); $this->assertEqual($this->terms[$i][$j]->id(), $tid); } } // Ensure the autocomplete input element appears when using the 'textfield' // type. $view = View::load('test_filter_taxonomy_index_tid'); $display =& $view->getDisplay('default'); $display['display_options']['filters']['tid']['type'] = 'textfield'; $view->save(); $this->drupalGet('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid'); $this->assertFieldByXPath('//input[@id="edit-options-value"]'); // Tests \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid::calculateDependencies(). $expected = ['config' => ['taxonomy.vocabulary.tags'], 'content' => ['taxonomy_term:tags:' . Term::load(2)->uuid()], 'module' => ['node', 'taxonomy', 'user']]; $this->assertIdentical($expected, $view->calculateDependencies()->getDependencies()); }
/** * Creates a comment, then tests the tokens generated from it. */ function testCommentTokenReplacement() { $token_service = \Drupal::token(); $language_interface = \Drupal::languageManager()->getCurrentLanguage(); $url_options = array('absolute' => TRUE, 'language' => $language_interface); // Setup vocabulary. Vocabulary::create(['vid' => 'tags', 'name' => 'Tags'])->save(); // Change the title of the admin user. $this->adminUser->name->value = 'This is a title with some special & > " stuff.'; $this->adminUser->save(); $this->drupalLogin($this->adminUser); // Set comment variables. $this->setCommentSubject(TRUE); // Create a node and a comment. $node = $this->drupalCreateNode(['type' => 'article', 'title' => '<script>alert("123")</script>']); $parent_comment = $this->postComment($node, $this->randomMachineName(), $this->randomMachineName(), TRUE); // Post a reply to the comment. $this->drupalGet('comment/reply/node/' . $node->id() . '/comment/' . $parent_comment->id()); $child_comment = $this->postComment(NULL, $this->randomMachineName(), $this->randomMachineName()); $comment = Comment::load($child_comment->id()); $comment->setHomepage('http://example.org/'); // Add HTML to ensure that sanitation of some fields tested directly. $comment->setSubject('<blink>Blinking Comment</blink>'); // Generate and test tokens. $tests = array(); $tests['[comment:cid]'] = $comment->id(); $tests['[comment:hostname]'] = $comment->getHostname(); $tests['[comment:author]'] = Html::escape($comment->getAuthorName()); $tests['[comment:mail]'] = $this->adminUser->getEmail(); $tests['[comment:homepage]'] = UrlHelper::filterBadProtocol($comment->getHomepage()); $tests['[comment:title]'] = Html::escape($comment->getSubject()); $tests['[comment:body]'] = $comment->comment_body->processed; $tests['[comment:langcode]'] = $comment->language()->getId(); $tests['[comment:url]'] = $comment->url('canonical', $url_options + array('fragment' => 'comment-' . $comment->id())); $tests['[comment:edit-url]'] = $comment->url('edit-form', $url_options); $tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', array('langcode' => $language_interface->getId())); $tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime(), array('langcode' => $language_interface->getId())); $tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations(), array('langcode' => $language_interface->getId())); $tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL; $tests['[comment:parent:title]'] = $parent_comment->getSubject(); $tests['[comment:entity]'] = Html::escape($node->getTitle()); // Test node specific tokens. $tests['[comment:entity:nid]'] = $comment->getCommentedEntityId(); $tests['[comment:entity:title]'] = Html::escape($node->getTitle()); $tests['[comment:author:uid]'] = $comment->getOwnerId(); $tests['[comment:author:name]'] = Html::escape($this->adminUser->getDisplayName()); $base_bubbleable_metadata = BubbleableMetadata::createFromObject($comment); $metadata_tests = []; $metadata_tests['[comment:cid]'] = $base_bubbleable_metadata; $metadata_tests['[comment:hostname]'] = $base_bubbleable_metadata; $bubbleable_metadata = clone $base_bubbleable_metadata; $bubbleable_metadata->addCacheableDependency($this->adminUser); $metadata_tests['[comment:author]'] = $bubbleable_metadata; $bubbleable_metadata = clone $base_bubbleable_metadata; $bubbleable_metadata->addCacheableDependency($this->adminUser); $metadata_tests['[comment:mail]'] = $bubbleable_metadata; $metadata_tests['[comment:homepage]'] = $base_bubbleable_metadata; $metadata_tests['[comment:title]'] = $base_bubbleable_metadata; $metadata_tests['[comment:body]'] = $base_bubbleable_metadata; $metadata_tests['[comment:langcode]'] = $base_bubbleable_metadata; $metadata_tests['[comment:url]'] = $base_bubbleable_metadata; $metadata_tests['[comment:edit-url]'] = $base_bubbleable_metadata; $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[comment:created]'] = $bubbleable_metadata->addCacheTags(['rendered']); $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[comment:created:since]'] = $bubbleable_metadata->setCacheMaxAge(0); $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[comment:changed:since]'] = $bubbleable_metadata->setCacheMaxAge(0); $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[comment:parent:cid]'] = $bubbleable_metadata->addCacheTags(['comment:1']); $metadata_tests['[comment:parent:title]'] = $bubbleable_metadata; $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[comment:entity]'] = $bubbleable_metadata->addCacheTags(['node:2']); // Test node specific tokens. $metadata_tests['[comment:entity:nid]'] = $bubbleable_metadata; $metadata_tests['[comment:entity:title]'] = $bubbleable_metadata; $bubbleable_metadata = clone $base_bubbleable_metadata; $metadata_tests['[comment:author:uid]'] = $bubbleable_metadata->addCacheTags(['user:2']); $metadata_tests['[comment:author:name]'] = $bubbleable_metadata; // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.'); foreach ($tests as $input => $expected) { $bubbleable_metadata = new BubbleableMetadata(); $output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId()), $bubbleable_metadata); $this->assertEqual($output, $expected, new FormattableMarkup('Comment token %token replaced.', ['%token' => $input])); $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]); } // Test anonymous comment author. $author_name = 'This is a random & " > string'; $comment->setOwnerId(0)->setAuthorName($author_name); $input = '[comment:author]'; $output = $token_service->replace($input, array('comment' => $comment), array('langcode' => $language_interface->getId())); $this->assertEqual($output, Html::escape($author_name), format_string('Comment author token %token replaced.', array('%token' => $input))); // Add comment field to user and term entities. $this->addDefaultCommentField('user', 'user', 'comment', CommentItemInterface::OPEN, 'comment_user'); $this->addDefaultCommentField('taxonomy_term', 'tags', 'comment', CommentItemInterface::OPEN, 'comment_term'); // Create a user and a comment. $user = User::create(['name' => 'alice']); $user->save(); $this->postComment($user, 'user body', 'user subject', TRUE); // Create a term and a comment. $term = Term::create(['vid' => 'tags', 'name' => 'term']); $term->save(); $this->postComment($term, 'term body', 'term subject', TRUE); // Load node, user and term again so comment_count gets computed. $node = Node::load($node->id()); $user = User::load($user->id()); $term = Term::load($term->id()); // Generate comment tokens for node (it has 2 comments, both new), // user and term. $tests = array(); $tests['[entity:comment-count]'] = 2; $tests['[entity:comment-count-new]'] = 2; $tests['[node:comment-count]'] = 2; $tests['[node:comment-count-new]'] = 2; $tests['[user:comment-count]'] = 1; $tests['[user:comment-count-new]'] = 1; $tests['[term:comment-count]'] = 1; $tests['[term:comment-count-new]'] = 1; foreach ($tests as $input => $expected) { $output = $token_service->replace($input, ['entity' => $node, 'node' => $node, 'user' => $user, 'term' => $term], ['langcode' => $language_interface->getId()]); $this->assertEqual($output, $expected, format_string('Comment token %token replaced.', ['%token' => $input])); } }
/** * {@inheritDoc} */ public function termDelete(\stdClass $term) { $term = Term::load($term->tid); $term->delete(); }
public function getTeam($teamId) { $result = array(); $team = Term::load($teamId); if ($team) { $result['team_title'] = $team->name->value; $result['team_type'] = $team->field_team_type->value; $result['weight'] = $team->getWeight(); // Generate list of team members. foreach ($this->getTeamUserIds($teamId) as $user_key => $uid) { $account = User::load($uid); // Exclude admin and anonymous users. if (!in_array($account->id(), array(0, 1))) { $result['members'][$user_key]['uid'] = $account->id(); $result['members'][$user_key]['field_first_name'] = $account->field_first_name->value; $result['members'][$user_key]['field_last_name'] = $account->field_last_name->value; $result['members'][$user_key]['field_job_title'] = $account->field_job_title->value; $result['members'][$user_key]['field_image'] = $account->user_picture->target_id ? file_create_url(File::load($account->user_picture->target_id)->uri->value) : NULL; $result['members'][$user_key]['field_position'] = Term::load($account->field_position->target_id)->name->value; } } } return $result; }
/** * {@inheritdoc} */ public function getLinks($base_plugin_definition = [], $include_base_plugin_id = FALSE) { /** @var $termStorage \Drupal\taxonomy\TermStorageInterface */ $termStorage = $this->entityManager()->getStorage('taxonomy_term'); // Load taxonomy terms for tax menu vocab. $terms = $termStorage->loadTree($this->getVocabulary()); $links = []; // Create menu links for each term in the vocabulary. foreach ($terms as $term) { if (!$term instanceof \Drupal\taxonomy\TermInterface) { $term = Term::load($term->tid); } $mlid = $this->buildMenuPluginId($term, $include_base_plugin_id); $links[$mlid] = $this->buildMenuDefinition($term, $base_plugin_definition); } return $links; }
/** * {@inheritdoc} */ public function termDelete(\stdClass $term) { $term = $term instanceof TermInterface ? $term : Term::load($term->tid); if ($term instanceof TermInterface) { $term->delete(); } }
/** * Create a stripe based on a taxonomy term. * * @param CalendarEvent $event */ function calendarTaxonomyStripe(&$event) { $colors = isset($this->options['colors']['calendar_colors_taxonomy']) ? $this->options['colors']['calendar_colors_taxonomy'] : []; if (empty($colors)) { return; } $entity = $event->getEntity(); $term_field_name = $this->options['colors']['taxonomy_field']; if ($entity->hasField($term_field_name) && ($terms_for_entity = $entity->get($term_field_name))) { /** @var EntityReferenceFieldItemListInterface $item */ foreach ($terms_for_entity as $item) { $tid = $item->getValue()['target_id']; $term = Term::load($tid); if (!array_key_exists($tid, $colors) || $colors[$tid] == CALENDAR_EMPTY_STRIPE) { continue; } $event->addStripeLabel($term->name->value); $event->addStripeHex($colors[$tid]); } } return; }
/** * Create a vocabulary and some taxonomy terms, ensuring they're loaded * correctly using entity_load_multiple(). */ function testTaxonomyTermMultipleLoad() { // Create a vocabulary. $vocabulary = $this->createVocabulary(); // Create five terms in the vocabulary. $i = 0; while ($i < 5) { $i++; $this->createTerm($vocabulary); } // Load the terms from the vocabulary. $terms = entity_load_multiple_by_properties('taxonomy_term', array('vid' => $vocabulary->id())); $count = count($terms); $this->assertEqual($count, 5, format_string('Correct number of terms were loaded. @count terms.', array('@count' => $count))); // Load the same terms again by tid. $terms2 = Term::loadMultiple(array_keys($terms)); $this->assertEqual($count, count($terms2), 'Five terms were loaded by tid.'); $this->assertEqual($terms, $terms2, 'Both arrays contain the same terms.'); // Remove one term from the array, then delete it. $deleted = array_shift($terms2); $deleted->delete(); $deleted_term = Term::load($deleted->id()); $this->assertFalse($deleted_term); // Load terms from the vocabulary by vid. $terms3 = entity_load_multiple_by_properties('taxonomy_term', array('vid' => $vocabulary->id())); $this->assertEqual(count($terms3), 4, 'Correct number of terms were loaded.'); $this->assertFalse(isset($terms3[$deleted->id()])); // Create a single term and load it by name. $term = $this->createTerm($vocabulary); $loaded_terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $term->getName())); $this->assertEqual(count($loaded_terms), 1, 'One term was loaded.'); $loaded_term = reset($loaded_terms); $this->assertEqual($term->id(), $loaded_term->id(), 'Term loaded by name successfully.'); }