/** * Builds an individual term item for the term item list depending on the formatter. * * @param \Drupal\taxonomy\Entity\Term $term * @return string */ private function buildTermListItem(Term $term, $formatter) { if ($formatter === 'linked') { $link_url = Url::fromRoute('entity.taxonomy_term.canonical', array('taxonomy_term' => $term->id())); return \Drupal::l($term->label(), $link_url); } return HTML::escape($term->label()); }
/** * Tests the plain formatter. */ public function testAllFormatters() { // Tests the plain formatter. $this->assertFormatterRdfa(array('type' => 'taxonomy_term_reference_plain'), 'http://schema.org/about', array('value' => $this->term->getName(), 'type' => 'literal')); // Tests the link formatter. $term_uri = $this->getAbsoluteUri($this->term); $this->assertFormatterRdfa(array('type' => 'taxonomy_term_reference_link'), 'http://schema.org/about', array('value' => $term_uri, 'type' => 'uri')); }
/** * Tests the plain formatter. */ public function testAllFormatters() { // Tests the plain formatter. $this->assertFormatterRdfa(array('type' => 'taxonomy_term_reference_plain'), 'http://schema.org/about', array('value' => $this->term->getName(), 'type' => 'literal')); // Grant the access content permission to the anonymous user. Role::create(array('id' => DRUPAL_ANONYMOUS_RID))->grantPermission('access content')->save(); // Tests the link formatter. $term_uri = $this->getAbsoluteUri($this->term); $this->assertFormatterRdfa(array('type' => 'taxonomy_term_reference_link'), 'http://schema.org/about', array('value' => $term_uri, 'type' => 'uri')); }
protected function setUp() { parent::setUp(); $this->installEntitySchema('taxonomy_term'); // We want an entity reference field. It needs a vocabulary, terms, a field // storage and a field. First, create the vocabulary. $vocabulary = Vocabulary::create(['vid' => Unicode::strtolower($this->randomMachineName())]); $vocabulary->save(); // Second, create the field. entity_test_create_bundle('test_bundle'); $this->fieldName = strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($vocabulary->id() => $vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('entity_test', 'test_bundle', $this->fieldName, NULL, 'taxonomy_term', 'default', $handler_settings); // Create two terms and also two accounts. for ($i = 0; $i <= 1; $i++) { $term = Term::create(['name' => $this->randomMachineName(), 'vid' => $vocabulary->id()]); $term->save(); $this->terms[] = $term; $this->accounts[] = $this->createUser(); } // Create three entity_test entities, the 0th entity will point to the // 0th account and 0th term, the 1st and 2nd entity will point to the // 1st account and 1st term. for ($i = 0; $i <= 2; $i++) { $entity = EntityTest::create(array('type' => 'test_bundle')); $entity->name->value = $this->randomMachineName(); $index = $i ? 1 : 0; $entity->user_id->target_id = $this->accounts[$index]->id(); $entity->{$this->fieldName}->target_id = $this->terms[$index]->id(); $entity->save(); $this->entities[] = $entity; } $this->factory = \Drupal::service('entity.query'); }
/** * Tests the Drupal 6 taxonomy term to Drupal 8 migration. */ public function testTaxonomyTerms() { $expected_results = array('1' => array('source_vid' => 1, 'vid' => 'vocabulary_1_i_0_', 'weight' => 0, 'parent' => array(0)), '2' => array('source_vid' => 2, 'vid' => 'vocabulary_2_i_1_', 'weight' => 3, 'parent' => array(0)), '3' => array('source_vid' => 2, 'vid' => 'vocabulary_2_i_1_', 'weight' => 4, 'parent' => array(2)), '4' => array('source_vid' => 3, 'vid' => 'vocabulary_3_i_2_', 'weight' => 6, 'parent' => array(0)), '5' => array('source_vid' => 3, 'vid' => 'vocabulary_3_i_2_', 'weight' => 7, 'parent' => array(4)), '6' => array('source_vid' => 3, 'vid' => 'vocabulary_3_i_2_', 'weight' => 8, 'parent' => array(4, 5))); $terms = Term::loadMultiple(array_keys($expected_results)); // Find each term in the tree. $storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); $vids = array_unique(array_column($expected_results, 'vid')); $tree_terms = []; foreach ($vids as $vid) { foreach ($storage->loadTree($vid) as $term) { $tree_terms[$term->tid] = $term; } } foreach ($expected_results as $tid => $values) { /** @var Term $term */ $term = $terms[$tid]; $this->assertIdentical("term {$tid} of vocabulary {$values['source_vid']}", $term->name->value); $this->assertIdentical("description of term {$tid} of vocabulary {$values['source_vid']}", $term->description->value); $this->assertIdentical($values['vid'], $term->vid->target_id); $this->assertIdentical((string) $values['weight'], $term->weight->value); if ($values['parent'] === array(0)) { $this->assertNull($term->parent->target_id); } else { $parents = array(); foreach (\Drupal::entityManager()->getStorage('taxonomy_term')->loadParents($tid) as $parent) { $parents[] = (int) $parent->id(); } $this->assertIdentical($parents, $values['parent']); } $this->assertArrayHasKey($tid, $tree_terms, "Term {$tid} exists in vocabulary tree"); $tree_term = $tree_terms[$tid]; $this->assertEquals($values['parent'], $tree_term->parents, "Term {$tid} has correct parents in vocabulary tree"); } }
protected function setUp() { parent::setUp(); $this->addDefaultCommentField('node', 'page'); $web_user = $this->drupalCreateUser(array('edit own page content', 'create page content')); $this->drupalLogin($web_user); // Add a vocabulary so we can test different view modes. $vocabulary = Vocabulary::create(['name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $this->randomMachineName(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'help' => '']); $vocabulary->save(); $this->vocabulary = $vocabulary; // Add a term to the vocabulary. $term = Term::create(['name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $this->vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); $term->save(); $this->term = $term; // Create an image field. FieldStorageConfig::create(['field_name' => 'field_image', 'entity_type' => 'node', 'type' => 'image', 'settings' => [], 'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED])->save(); $field_config = FieldConfig::create(['field_name' => 'field_image', 'label' => 'Images', 'entity_type' => 'node', 'bundle' => 'page', 'required' => FALSE, 'settings' => []]); $field_config->save(); // Create a field. $this->fieldName = Unicode::strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($this->vocabulary->id() => $this->vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('node', 'page', $this->fieldName, 'Tags', 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); entity_get_form_display('node', 'page', 'default')->setComponent($this->fieldName, array('type' => 'entity_reference_autocomplete_tags'))->save(); // Show on default display and teaser. entity_get_display('node', 'page', 'default')->setComponent($this->fieldName, array('type' => 'entity_reference_label'))->save(); entity_get_display('node', 'page', 'teaser')->setComponent($this->fieldName, array('type' => 'entity_reference_label'))->save(); entity_get_form_display('node', 'page', 'default')->setComponent('field_image', array('type' => 'image_image', 'settings' => []))->save(); entity_get_display('node', 'page', 'default')->setComponent('field_image')->save(); }
/** * 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 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 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'); } }
/** * Returns a new term with random properties in vocabulary $vid. * * @param \Drupal\taxonomy\Entity\Vocabulary $vocabulary * The vocabulary object. * @param array $values * (optional) An array of values to set, keyed by property name. If the * entity type has bundles, the bundle key has to be specified. * * @return \Drupal\taxonomy\Entity\Term * The new taxonomy term object. */ function createTerm(Vocabulary $vocabulary, $values = array()) { $filter_formats = filter_formats(); $format = array_pop($filter_formats); $term = Term::create($values + ['name' => $this->randomMachineName(), 'description' => ['value' => $this->randomMachineName(), 'format' => $format->id()], 'vid' => $vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); $term->save(); return $term; }
/** * Tests if forum module uninstallation properly deletes the field. */ public function testForumUninstallWithField() { $this->drupalLogin($this->drupalCreateUser(['administer taxonomy', 'administer nodes', 'administer modules', 'delete any forum content', 'administer content types'])); // Ensure that the field exists before uninstallation. $field_storage = FieldStorageConfig::loadByName('node', 'taxonomy_forums'); $this->assertNotNull($field_storage, 'The taxonomy_forums field storage exists.'); // Create a taxonomy term. $term = Term::create(['name' => t('A term'), 'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(), 'description' => '', 'parent' => array(0), 'vid' => 'forums', 'forum_container' => 0]); $term->save(); // Create a forum node. $node = $this->drupalCreateNode(array('title' => 'A forum post', 'type' => 'forum', 'taxonomy_forums' => array(array('target_id' => $term->id())))); // Create at least one comment against the forum node. $comment = Comment::create(array('entity_id' => $node->nid->value, 'entity_type' => 'node', 'field_name' => 'comment_forum', 'pid' => 0, 'uid' => 0, 'status' => CommentInterface::PUBLISHED, 'subject' => $this->randomMachineName(), 'hostname' => '127.0.0.1')); $comment->save(); // Attempt to uninstall forum. $this->drupalGet('admin/modules/uninstall'); // Assert forum is required. $this->assertNoFieldByName('uninstall[forum]'); $this->assertText('To uninstall Forum, first delete all Forum content'); // Delete the node. $this->drupalPostForm('node/' . $node->id() . '/delete', array(), t('Delete')); // Attempt to uninstall forum. $this->drupalGet('admin/modules/uninstall'); // Assert forum is still required. $this->assertNoFieldByName('uninstall[forum]'); $this->assertText('To uninstall Forum, first delete all Forums terms'); // Delete any forum terms. $vid = $this->config('forum.settings')->get('vocabulary'); $terms = entity_load_multiple_by_properties('taxonomy_term', ['vid' => $vid]); foreach ($terms as $term) { $term->delete(); } // Ensure that the forum node type can not be deleted. $this->drupalGet('admin/structure/types/manage/forum'); $this->assertNoLink(t('Delete')); // Now attempt to uninstall forum. $this->drupalGet('admin/modules/uninstall'); // Assert forum is no longer required. $this->assertFieldByName('uninstall[forum]'); $this->drupalPostForm('admin/modules/uninstall', array('uninstall[forum]' => 1), t('Uninstall')); $this->drupalPostForm(NULL, [], t('Uninstall')); // Check that the field is now deleted. $field_storage = FieldStorageConfig::loadByName('node', 'taxonomy_forums'); $this->assertNull($field_storage, 'The taxonomy_forums field storage has been deleted.'); // Check that a node type with a machine name of forum can be created after // uninstalling the forum module and the node type is not locked. $edit = array('name' => 'Forum', 'title_label' => 'title for forum', 'type' => 'forum'); $this->drupalPostForm('admin/structure/types/add', $edit, t('Save content type')); $this->assertTrue((bool) NodeType::load('forum'), 'Node type with machine forum created.'); $this->drupalGet('admin/structure/types/manage/forum'); $this->clickLink(t('Delete')); $this->drupalPostForm(NULL, array(), t('Delete')); $this->assertResponse(200); $this->assertFalse((bool) NodeType::load('forum'), 'Node type with machine forum deleted.'); // Double check everything by reinstalling the forum module again. $this->drupalPostForm('admin/modules', ['modules[Core][forum][enable]' => 1], 'Install'); $this->assertText('Module Forum has been enabled.'); }
public function titleQuery() { $titles = array(); $terms = Term::loadMultiple($this->value); foreach ($terms as $term) { $titles[] = \Drupal::entityManager()->getTranslationFromContext($term)->label(); } return $titles; }
protected function setUp() { parent::setUp(); $this->installEntitySchema('entity_test_rev'); entity_reference_create_field($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType); // Add the mapping. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping($this->fieldName, array('properties' => array('schema:knows')))->save(); // Create the entity to be referenced. $this->target_entity = entity_create($this->entityType, array('name' => $this->randomMachineName())); $this->target_entity->save(); // Create the entity that will have the entity reference field. $this->entity = entity_create($this->entityType, array('name' => $this->randomMachineName())); $this->entity->save(); $this->entity->{$this->fieldName}->entity = $this->target_entity; $this->entity->{$this->fieldName}->access = TRUE; $this->uri = $this->getAbsoluteUri($this->entity); }
/** * 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); }
/** * {@inheritdoc} */ protected function createEntity() { // Create a "Camelids" vocabulary. $vocabulary = Vocabulary::create(['name' => 'Camelids', 'vid' => 'camelids']); $vocabulary->save(); // Create a "Llama" taxonomy term. $term = Term::create(['name' => 'Llama', 'vid' => $vocabulary->id()]); $term->save(); return $term; }
protected function setUp() { parent::setUp(); $this->installEntitySchema('entity_test_rev'); // Give anonymous users permission to view test entities. $this->installConfig(array('user')); Role::load(RoleInterface::ANONYMOUS_ID)->grantPermission('view test entity')->save(); $this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType); // Add the mapping. $mapping = rdf_get_mapping('entity_test', 'entity_test'); $mapping->setFieldMapping($this->fieldName, array('properties' => array('schema:knows')))->save(); // Create the entity to be referenced. $this->targetEntity = entity_create($this->entityType, array('name' => $this->randomMachineName())); $this->targetEntity->save(); // Create the entity that will have the entity reference field. $this->entity = entity_create($this->entityType, array('name' => $this->randomMachineName())); $this->entity->save(); $this->entity->{$this->fieldName}->entity = $this->targetEntity; $this->uri = $this->getAbsoluteUri($this->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)); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(FALSE); // Setup vocabulary and terms so the initial import is valid. Vocabulary::create(['vid' => 'tags', 'name' => 'Tags'])->save(); // This will get a term ID of 3. $term = Term::create(['vid' => 'tags', 'name' => 'muh']); $term->save(); // This will get a term ID of 4. $this->terms[$term->id()] = $term; $term = Term::create(['vid' => 'tags', 'name' => 'muh']); $term->save(); $this->terms[$term->id()] = $term; ViewTestData::createTestViews(get_class($this), array('taxonomy_test_views')); }
/** * 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); } }
/** * Tests the entity row handler. */ public function testEntityRow() { $vocab = Vocabulary::create(['name' => $this->randomMachineName(), 'vid' => strtolower($this->randomMachineName())]); $vocab->save(); $term = Term::create(['name' => $this->randomMachineName(), 'vid' => $vocab->id()]); $term->save(); $view = Views::getView('test_entity_row'); $build = $view->preview(); $this->render($build); $this->assertText($term->getName(), 'The rendered entity appears as row in the view.'); // Tests the available view mode options. $form = array(); $form_state = new FormState(); $form_state->set('view', $view->storage); $view->rowPlugin->buildOptionsForm($form, $form_state); $this->assertTrue(isset($form['view_mode']['#options']['default']), 'Ensure that the default view mode is available'); }
/** * {@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); }
/** * Tests the normalization of terms. */ public function testTerm() { $vocabulary = Vocabulary::create(['vid' => 'example_vocabulary']); $vocabulary->save(); $account = User::create(['name' => $this->randomMachineName()]); $account->save(); // @todo Until https://www.drupal.org/node/2327935 is fixed, if no parent is // set, the test fails because target_id => 0 is reserialized to NULL. $term_parent = Term::create(['name' => $this->randomMachineName(), 'vid' => $vocabulary->id()]); $term_parent->save(); $term = Term::create(['name' => $this->randomMachineName(), 'vid' => $vocabulary->id(), 'description' => array('value' => $this->randomMachineName(), 'format' => $this->randomMachineName()), 'parent' => $term_parent->id()]); $term->save(); $original_values = $term->toArray(); $normalized = $this->serializer->normalize($term, $this->format, ['account' => $account]); /** @var \Drupal\taxonomy\TermInterface $denormalized_term */ $denormalized_term = $this->serializer->denormalize($normalized, 'Drupal\\taxonomy\\Entity\\Term', $this->format, ['account' => $account]); $this->assertEqual($original_values, $denormalized_term->toArray(), 'Term values are restored after normalizing and denormalizing.'); }
/** * 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.'); }
/** * Test that URL altering works and that it occurs in the correct order. */ function testUrlAlter() { // Ensure that the url_alias table exists after Drupal installation. $this->assertTrue(Database::getConnection()->schema()->tableExists('url_alias'), 'The url_alias table exists after Drupal installation.'); // User names can have quotes and plus signs so we should ensure that URL // altering works with this. $account = $this->drupalCreateUser(array('administer url aliases'), "a'foo+bar"); $this->drupalLogin($account); $uid = $account->id(); $name = $account->getUsername(); // Test a single altered path. $this->drupalGet("user/{$name}"); $this->assertResponse('200', 'The user/username path gets resolved correctly'); $this->assertUrlOutboundAlter("/user/{$uid}", "/user/{$name}"); // Test that a path always uses its alias. $path = array('source' => "/user/{$uid}/test1", 'alias' => '/alias/test1'); $this->container->get('path.alias_storage')->save($path['source'], $path['alias']); $this->rebuildContainer(); $this->assertUrlInboundAlter('/alias/test1', "/user/{$uid}/test1"); $this->assertUrlOutboundAlter("/user/{$uid}/test1", '/alias/test1'); // Test adding an alias via the UI. $edit = array('source' => "/user/{$uid}/edit", 'alias' => '/alias/test2'); $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save')); $this->assertText(t('The alias has been saved.')); $this->drupalGet('alias/test2'); $this->assertResponse('200', 'The path alias gets resolved correctly'); $this->assertUrlOutboundAlter("/user/{$uid}/edit", '/alias/test2'); // Test a non-existent user is not altered. $uid++; $this->assertUrlOutboundAlter("/user/{$uid}", "/user/{$uid}"); // Test that 'forum' is altered to 'community' correctly, both at the root // level and for a specific existing forum. $this->drupalGet('community'); $this->assertText('General discussion', 'The community path gets resolved correctly'); $this->assertUrlOutboundAlter('/forum', '/community'); $forum_vid = $this->config('forum.settings')->get('vocabulary'); $term_name = $this->randomMachineName(); $term = Term::create(['name' => $term_name, 'vid' => $forum_vid]); $term->save(); $this->drupalGet("community/" . $term->id()); $this->assertText($term_name, 'The community/{tid} path gets resolved correctly'); $this->assertUrlOutboundAlter("/forum/" . $term->id(), "/community/" . $term->id()); }
/** * Check access for taxonomy fields. */ public function testTermFields() { $vocab = Vocabulary::create(['vid' => 'random', 'name' => 'Randomness']); $vocab->save(); $term1 = Term::create(['name' => 'Semi random', 'vid' => $vocab->id()]); $term1->save(); $term2 = Term::create(['name' => 'Majorly random', 'vid' => $vocab->id()]); $term2->save(); $term3 = Term::create(['name' => 'Not really random', 'vid' => $vocab->id()]); $term3->save(); $this->assertFieldAccess('taxonomy_term', 'name', 'Majorly random'); $this->assertFieldAccess('taxonomy_term', 'name', 'Semi random'); $this->assertFieldAccess('taxonomy_term', 'name', 'Not really random'); $this->assertFieldAccess('taxonomy_term', 'tid', $term1->id()); $this->assertFieldAccess('taxonomy_term', 'tid', $term2->id()); $this->assertFieldAccess('taxonomy_term', 'tid', $term3->id()); $this->assertFieldAccess('taxonomy_term', 'uuid', $term1->uuid()); $this->assertFieldAccess('taxonomy_term', 'uuid', $term2->uuid()); $this->assertFieldAccess('taxonomy_term', 'uuid', $term3->uuid()); }
/** * 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); }
/** * 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.'); }