/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('uc_catalog.settings'); $view = Views::getView('uc_catalog'); $view->initDisplay(); $displays = array(); foreach ($view->displayHandlers as $display) { if ($display->getPluginId() == 'page') { $displays[$display->display['id']] = $display->display['display_title']; } } $form['uc_catalog_display'] = array('#type' => 'select', '#title' => $this->t('Catalog display'), '#default_value' => $config->get('display'), '#options' => $displays); $vid = $config->get('vocabulary'); if ($vid) { $catalog = Vocabulary::load($vid); $form['catalog_vid'] = array('#markup' => '<p>' . $this->t('The taxonomy vocabulary <a href=":edit-url">%name</a> is set as the product catalog.', [':edit-url' => Url::fromRoute('entity.taxonomy_vocabulary.edit_form', ['taxonomy_vocabulary' => $catalog->id()])->toString(), '%name' => $catalog->label()]) . '</p>'); } $vocabs = array(); $vocabularies = Vocabulary::loadMultiple(); foreach ($vocabularies as $vid => $vocabulary) { $vocabs[$vid] = $vocabulary->label(); } $form['uc_catalog_vid'] = array('#type' => 'select', '#title' => $this->t('Catalog vocabulary'), '#default_value' => $config->get('vocabulary'), '#options' => $vocabs); $form['uc_catalog_breadcrumb'] = array('#type' => 'checkbox', '#title' => $this->t('Display the catalog breadcrumb'), '#default_value' => $config->get('breadcrumb')); return parent::buildForm($form, $form_state); }
/** * Test terms in a single and multiple hierarchy. */ function testTaxonomyTermHierarchy() { // Create two taxonomy terms. $term1 = $this->createTerm($this->vocabulary); $term2 = $this->createTerm($this->vocabulary); // Check that hierarchy is flat. $vocabulary = Vocabulary::load($this->vocabulary->id()); $this->assertEqual(0, $vocabulary->getHierarchy(), 'Vocabulary is flat.'); // Edit $term2, setting $term1 as parent. $edit = array(); $edit['parent[]'] = array($term1->id()); $this->drupalPostForm('taxonomy/term/' . $term2->id() . '/edit', $edit, t('Save')); // Check the hierarchy. $children = taxonomy_term_load_children($term1->id()); $parents = taxonomy_term_load_parents($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_term_load_parents($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 = array($term1->id(), $term3->id()); $term2->save(); $parents = taxonomy_term_load_parents($term2->id()); $this->assertTrue(isset($parents[$term1->id()]) && isset($parents[$term3->id()]), 'Both parents found successfully.'); }
/** * Validate a migrated vocabulary contains the expected values. * * @param $id * Entity ID to load and check. * @param $expected_label * The label the migrated entity should have. * @param $expected_description * The description the migrated entity should have. * @param $expected_hierarchy * The hierarchy setting the migrated entity should have. * @param $expected_weight * The weight the migrated entity should have. */ protected function assertEntity($id, $expected_label, $expected_description, $expected_hierarchy, $expected_weight) { /** @var \Drupal\taxonomy\VocabularyInterface $entity */ $entity = Vocabulary::load($id); $this->assertTrue($entity instanceof VocabularyInterface); $this->assertIdentical($expected_label, $entity->label()); $this->assertIdentical($expected_description, $entity->getDescription()); $this->assertIdentical($expected_hierarchy, $entity->getHierarchy()); $this->assertIdentical($expected_weight, $entity->get('weight')); }
function testViewsHandlerVidField() { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $view = Views::getView('test_taxonomy_vid_field'); $this->executeView($view); $actual = $renderer->executeInRenderContext(new RenderContext(), function () use($view) { return $view->field['vid']->advancedRender($view->result[0]); }); $vocabulary = Vocabulary::load($this->term1->getVocabularyId()); $expected = $vocabulary->get('name'); $this->assertEqual($expected, $actual); }
/** * Tests token replacement in the "all terms" field handler. */ public function testViewsHandlerAllTermsWithTokens() { $view = Views::getView('taxonomy_all_terms_test'); $this->drupalGet('taxonomy_all_terms_token_test'); // Term itself: {{ term_node_tid }} $this->assertText('Term: ' . $this->term1->getName()); // The taxonomy term ID for the term: {{ term_node_tid__tid }} $this->assertText('The taxonomy term ID for the term: ' . $this->term1->id()); // The taxonomy term name for the term: {{ term_node_tid__name }} $this->assertText('The taxonomy term name for the term: ' . $this->term1->getName()); // The machine name for the vocabulary the term belongs to: {{ term_node_tid__vocabulary_vid }} $this->assertText('The machine name for the vocabulary the term belongs to: ' . $this->term1->getVocabularyId()); // The name for the vocabulary the term belongs to: {{ term_node_tid__vocabulary }} $vocabulary = Vocabulary::load($this->term1->bundle()); $this->assertText('The name for the vocabulary the term belongs to: ' . $vocabulary->label()); }
/** * Tests the Drupal 6 taxonomy vocabularies to Drupal 8 migration. */ public function testTaxonomyVocabulary() { for ($i = 0; $i < 3; $i++) { $j = $i + 1; $vocabulary = Vocabulary::load("vocabulary_{$j}_i_{$i}_"); $this->assertIdentical(Migration::load('d6_taxonomy_vocabulary')->getIdMap()->lookupDestinationID(array($j)), array($vocabulary->id())); $this->assertIdentical("vocabulary {$j} (i={$i})", $vocabulary->label()); $this->assertIdentical("description of vocabulary {$j} (i={$i})", $vocabulary->getDescription()); $this->assertIdentical($i, $vocabulary->getHierarchy()); $this->assertIdentical(4 + $i, $vocabulary->get('weight')); } $vocabulary = Vocabulary::load('vocabulary_name_much_longer_than'); $this->assertIdentical('vocabulary name much longer than thirty two characters', $vocabulary->label()); $this->assertIdentical('description of vocabulary name much longer than thirty two characters', $vocabulary->getDescription()); $this->assertIdentical(3, $vocabulary->getHierarchy()); $this->assertIdentical(7, $vocabulary->get('weight')); }
/** * {@inheritdoc} */ public function getSettableOptions(AccountInterface $account = NULL) { if ($callback = $this->getSetting('options_list_callback')) { return call_user_func_array($callback, array($this->getFieldDefinition(), $this->getEntity())); } else { $options = array(); foreach ($this->getSetting('allowed_values') as $tree) { if ($vocabulary = Vocabulary::load($tree['vocabulary'])) { if ($terms = taxonomy_get_tree($vocabulary->id(), $tree['parent'], NULL, TRUE)) { foreach ($terms as $term) { $options[$term->id()] = str_repeat('-', $term->depth) . $term->getName(); } } } } return $options; } }
/** * @param $contentTypes * @param $limit * @param $titleWords * @param $timeRange * * @return array */ public function createTerm($vocabularies, $limit, $nameWords) { $terms = []; $values = []; for ($i = 0; $i < $limit; $i++) { $vocabulary = Vocabulary::load($vocabularies[array_rand($vocabularies)]); $filter_formats = filter_formats(); $format = array_pop($filter_formats); $term = entity_create('taxonomy_term', $values + array('name' => $this->getRandom()->sentences(mt_rand(1, $nameWords), true), 'description' => array('value' => $this->getRandom()->sentences(), 'format' => $format->id()), 'vid' => $vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); try { $term->save(); $terms['success'][] = ['tid' => $term->id(), 'vocabulary' => $vocabulary->get('name'), 'name' => $term->getName()]; } catch (\Exception $error) { $terms['error'][] = ['vocabulary' => $vocabularies[$vocabulary], 'name' => $term->getName(), 'error' => $error->getMessage()]; } } return $terms; }
/** * Ensure that the vocabulary static reset works correctly. */ function testTaxonomyVocabularyLoadStaticReset() { $original_vocabulary = Vocabulary::load($this->vocabulary->id()); $this->assertTrue(is_object($original_vocabulary), 'Vocabulary loaded successfully.'); $this->assertEqual($this->vocabulary->label(), $original_vocabulary->label(), 'Vocabulary loaded successfully.'); // Change the name and description. $vocabulary = $original_vocabulary; $vocabulary->set('name', $this->randomMachineName()); $vocabulary->set('description', $this->randomMachineName()); $vocabulary->save(); // Load the vocabulary. $new_vocabulary = Vocabulary::load($original_vocabulary->id()); $this->assertEqual($new_vocabulary->label(), $vocabulary->label(), 'The vocabulary was loaded.'); // Delete the vocabulary. $this->vocabulary->delete(); $vocabularies = Vocabulary::loadMultiple(); $this->assertTrue(!isset($vocabularies[$this->vocabulary->id()]), 'The vocabulary was deleted.'); }
/** * Test xmlsitemap settings for taxonomies. */ public function testTaxonomySettings() { $this->drupalLogin($this->admin_user); $this->drupalGet('admin/structure/taxonomy/add'); $this->assertField('xmlsitemap[status]'); $this->assertField('xmlsitemap[priority]'); $edit = array('name' => $this->randomMachineName(), 'vid' => Unicode::strtolower($this->randomMachineName()), 'xmlsitemap[status]' => '1', 'xmlsitemap[priority]' => '1.0'); $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertText("Created new vocabulary {$edit['name']}."); $vocabulary = \Drupal\taxonomy\Entity\Vocabulary::load($edit['vid']); xmlsitemap_link_bundle_enable('taxonomy_term', $vocabulary->id()); $this->drupalGet('admin/structure/taxonomy/manage/' . $vocabulary->id() . '/add'); $this->assertResponse(200); $this->assertField('xmlsitemap[status]'); $this->assertField('xmlsitemap[priority]'); $this->assertField('xmlsitemap[changefreq]'); $edit = array('name[0][value]' => $this->randomMachineName(), 'xmlsitemap[status]' => 'default', 'xmlsitemap[priority]' => 'default'); $this->drupalPostForm(NULL, $edit, t('Save')); }
/** * {@inheritdoc} */ public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { if ($match || $limit) { return parent::getReferenceableEntities($match, $match_operator, $limit); } $options = array(); $bundles = $this->entityManager->getBundleInfo('taxonomy_term'); $handler_settings = $this->configuration['handler_settings']; $bundle_names = !empty($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : array_keys($bundles); foreach ($bundle_names as $bundle) { if ($vocabulary = Vocabulary::load($bundle)) { if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) { foreach ($terms as $term) { $options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . String::checkPlain($term->getName()); } } } } return $options; }
/** * Tests alias functionality through the admin interfaces. */ function testTermAlias() { // Create a term in the default 'Tags' vocabulary with URL alias. $vocabulary = Vocabulary::load('tags'); $description = $this->randomMachineName(); $edit = array('name[0][value]' => $this->randomMachineName(), 'description[0][value]' => $description, 'path[0][alias]' => '/' . $this->randomMachineName()); $this->drupalPostForm('admin/structure/taxonomy/manage/' . $vocabulary->id() . '/add', $edit, t('Save')); $tid = db_query("SELECT tid FROM {taxonomy_term_field_data} WHERE name = :name AND default_langcode = 1", array(':name' => $edit['name[0][value]']))->fetchField(); // Confirm that the alias works. $this->drupalGet($edit['path[0][alias]']); $this->assertText($description, 'Term can be accessed on URL alias.'); // Confirm the 'canonical' and 'shortlink' URLs. $elements = $this->xpath("//link[contains(@rel, 'canonical') and contains(@href, '" . $edit['path[0][alias]'] . "')]"); $this->assertTrue(!empty($elements), 'Term page contains canonical link URL.'); $elements = $this->xpath("//link[contains(@rel, 'shortlink') and contains(@href, 'taxonomy/term/" . $tid . "')]"); $this->assertTrue(!empty($elements), 'Term page contains shortlink URL.'); // Change the term's URL alias. $edit2 = array(); $edit2['path[0][alias]'] = '/' . $this->randomMachineName(); $this->drupalPostForm('taxonomy/term/' . $tid . '/edit', $edit2, t('Save')); // Confirm that the changed alias works. $this->drupalGet(trim($edit2['path[0][alias]'], '/')); $this->assertText($description, 'Term can be accessed on changed URL alias.'); // Confirm that the old alias no longer works. $this->drupalGet(trim($edit['path[0][alias]'], '/')); $this->assertNoText($description, 'Old URL alias has been removed after altering.'); $this->assertResponse(404, 'Old URL alias returns 404.'); // Remove the term's URL alias. $edit3 = array(); $edit3['path[0][alias]'] = ''; $this->drupalPostForm('taxonomy/term/' . $tid . '/edit', $edit3, t('Save')); // Confirm that the alias no longer works. $this->drupalGet(trim($edit2['path[0][alias]'], '/')); $this->assertNoText($description, 'Old URL alias has been removed after altering.'); $this->assertResponse(404, 'Old URL alias returns 404.'); }
/** * {@inheritdoc} */ public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { if ($match || $limit) { $this->configuration['handler_settings']['sort'] = ['field' => 'name', 'direction' => 'asc']; return parent::getReferenceableEntities($match, $match_operator, $limit); } $options = array(); $bundles = $this->entityManager->getBundleInfo('taxonomy_term'); $handler_settings = $this->configuration['handler_settings']; $bundle_names = !empty($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : array_keys($bundles); foreach ($bundle_names as $bundle) { if ($vocabulary = Vocabulary::load($bundle)) { if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) { foreach ($terms as $term) { $options[$vocabulary->id()][$term->id()] = str_repeat('-', $term->depth) . Html::escape($this->entityManager->getTranslationFromContext($term)->label()); } } } } return $options; }
/** * Deleting a vocabulary. */ function testTaxonomyAdminDeletingVocabulary() { // Create a vocabulary. $vid = Unicode::strtolower($this->randomMachineName()); $edit = array('name' => $this->randomMachineName(), 'vid' => $vid); $this->drupalPostForm('admin/structure/taxonomy/add', $edit, t('Save')); $this->assertText(t('Created new vocabulary'), 'New vocabulary was created.'); // Check the created vocabulary. $this->container->get('entity.manager')->getStorage('taxonomy_vocabulary')->resetCache(); $vocabulary = Vocabulary::load($vid); $this->assertTrue($vocabulary, 'Vocabulary found.'); // Delete the vocabulary. $this->drupalGet('admin/structure/taxonomy/manage/' . $vocabulary->id()); $this->clickLink(t('Delete')); $this->assertRaw(t('Are you sure you want to delete the vocabulary %name?', array('%name' => $vocabulary->label())), '[confirm deletion] Asks for confirmation.'); $this->assertText(t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'), '[confirm deletion] Inform that all terms will be deleted.'); // Confirm deletion. $this->drupalPostForm(NULL, NULL, t('Delete')); $this->assertRaw(t('Deleted vocabulary %name.', array('%name' => $vocabulary->label())), 'Vocabulary deleted.'); $this->container->get('entity.manager')->getStorage('taxonomy_vocabulary')->resetCache(); $this->assertFalse(Vocabulary::load($vid), 'Vocabulary not found.'); }
/** * 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()); }
/** * {@inheritdoc} */ protected function valueForm(&$form, FormStateInterface $form_state) { parent::valueForm($form, $form_state); if (!empty($this->definition['vocabulary'])) { $vocabulary = Vocabulary::load($this->definition['vocabulary']); $title = $this->t('Select terms from vocabulary @voc', array('@voc' => $vocabulary->label())); } else { $vocabulary = FALSE; $title = $this->t('Select terms'); } $form['value']['#title'] = $title; if ($vocabulary && $this->options['type'] == 'textfield') { $form['value']['#autocomplete_path'] = 'admin/views/ajax/autocomplete/taxonomy/' . $vocabulary->id(); } else { if ($vocabulary && !empty($this->options['hierarchy'])) { /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */ $term_storage = \Drupal::entityManager()->getStorage('taxonomy_term'); $tree = $term_storage->loadTree($vocabulary->id()); $options = array(); if ($tree) { foreach ($tree as $term) { $choice = new \stdClass(); $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name); $options[] = $choice; } } } else { $options = array(); $query = db_select('taxonomy_term_data', 'td'); $query->innerJoin('taxonomy_vocabulary', 'tv', 'td.vid = tv.vid'); $query->fields('td'); $query->orderby('tv.weight'); $query->orderby('tv.name'); $query->orderby('td.weight'); $query->orderby('td.name'); $query->addTag('term_access'); if ($vocabulary) { $query->condition('tv.vid', $vocabulary->id()); } $result = $query->execute(); foreach ($result as $term) { $options[$term->tid] = $term->name; } } $default_value = (array) $this->value; if ($form_state->get('exposed')) { $identifier = $this->options['expose']['identifier']; if (!empty($this->options['expose']['reduce'])) { $options = $this->reduceValueOptions($options); if (!empty($this->options['expose']['multiple']) && empty($this->options['expose']['required'])) { $default_value = array(); } } if (empty($this->options['expose']['multiple'])) { if (empty($this->options['expose']['required']) && (empty($default_value) || !empty($this->options['expose']['reduce']))) { $default_value = 'All'; } elseif (empty($default_value)) { $keys = array_keys($options); $default_value = array_shift($keys); } elseif ($default_value == array('')) { $default_value = 'All'; } else { $copy = $default_value; $default_value = array_shift($copy); } } } $form['value']['#type'] = 'select'; $form['value']['#multiple'] = TRUE; $form['value']['#options'] = $options; $form['value']['#size'] = min(9, count($options)); $form['value']['#default_value'] = $default_value; $input =& $form_state->getUserInput(); if ($form_state->get('exposed') && isset($identifier) && !isset($input[$identifier])) { $input[$identifier] = $default_value; } } }
/** * {@inheritdoc} */ public function settingsSummary($settings) { $config = $this->getConfiguration(); $no_selection = array('No vocabulary selected.'); if (isset($config['vocabulary']) && $config['vocabulary']) { $vocabulary = Vocabulary::load($config['vocabulary']); return $vocabulary ? array('Vocabulary: ' . $vocabulary->label()) : $no_selection; } return $no_selection; }
/** * Edits the forum taxonomy. */ function editForumVocabulary() { // Backup forum taxonomy. $vid = $this->config('forum.settings')->get('vocabulary'); $original_vocabulary = Vocabulary::load($vid); // Generate a random name and description. $edit = array('name' => $this->randomMachineName(10), 'description' => $this->randomMachineName(100)); // Edit the vocabulary. $this->drupalPostForm('admin/structure/taxonomy/manage/' . $original_vocabulary->id(), $edit, t('Save')); $this->assertResponse(200); $this->assertRaw(t('Updated vocabulary %name.', array('%name' => $edit['name'])), 'Vocabulary was edited'); // Grab the newly edited vocabulary. $current_vocabulary = Vocabulary::load($vid); // Make sure we actually edited the vocabulary properly. $this->assertEqual($current_vocabulary->label(), $edit['name'], 'The name was updated'); $this->assertEqual($current_vocabulary->getDescription(), $edit['description'], 'The description was updated'); // Restore the original vocabulary's name and description. $current_vocabulary->set('name', $original_vocabulary->label()); $current_vocabulary->set('description', $original_vocabulary->getDescription()); $current_vocabulary->save(); // Reload vocabulary to make sure changes are saved. $current_vocabulary = Vocabulary::load($vid); $this->assertEqual($current_vocabulary->label(), $original_vocabulary->label(), 'The original vocabulary settings were restored'); }
/** * 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 the entity reference field type for referencing config entities. */ public function testConfigEntityReferenceItem() { $referenced_entity_id = $this->vocabulary->id(); // Just being able to create the entity like this verifies a lot of code. $entity = EntityTest::create(); $entity->field_test_taxonomy_vocabulary->target_id = $referenced_entity_id; $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = entity_load('entity_test', $entity->id()); $this->assertTrue($entity->field_test_taxonomy_vocabulary instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->field_test_taxonomy_vocabulary[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->field_test_taxonomy_vocabulary->target_id, $referenced_entity_id); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $this->vocabulary->label()); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $referenced_entity_id); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->uuid(), $this->vocabulary->uuid()); // Change the name of the term via the reference. $new_name = $this->randomMachineName(); $entity->field_test_taxonomy_vocabulary->entity->set('name', $new_name); $entity->field_test_taxonomy_vocabulary->entity->save(); // Verify it is the correct name. $vocabulary = Vocabulary::load($referenced_entity_id); $this->assertEqual($vocabulary->label(), $new_name); // Make sure the computed term reflects updates to the term id. $vocabulary2 = $vocabulary = Vocabulary::create(['name' => $this->randomMachineName(), 'vid' => Unicode::strtolower($this->randomMachineName()), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); $vocabulary2->save(); $entity->field_test_taxonomy_vocabulary->target_id = $vocabulary2->id(); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $vocabulary2->id()); $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $vocabulary2->label()); // Delete terms so we have nothing to reference and try again $this->vocabulary->delete(); $vocabulary2->delete(); $entity = EntityTest::create(array('name' => $this->randomMachineName())); $entity->save(); }
/** * Tests hook invocations for CRUD operations on taxonomy vocabularies. */ public function testTaxonomyVocabularyHooks() { $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')); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_vocabulary_create called', 'entity_crud_hook_test_entity_create called for type taxonomy_vocabulary')); $GLOBALS['entity_crud_hook_test'] = array(); $vocabulary->save(); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_vocabulary_presave called', 'entity_crud_hook_test_entity_presave called for type taxonomy_vocabulary', 'entity_crud_hook_test_taxonomy_vocabulary_insert called', 'entity_crud_hook_test_entity_insert called for type taxonomy_vocabulary')); $GLOBALS['entity_crud_hook_test'] = array(); $vocabulary = Vocabulary::load($vocabulary->id()); $this->assertHookMessageOrder(array('entity_crud_hook_test_entity_load called for type taxonomy_vocabulary', 'entity_crud_hook_test_taxonomy_vocabulary_load called')); $GLOBALS['entity_crud_hook_test'] = array(); $vocabulary->set('name', 'New name'); $vocabulary->save(); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_vocabulary_presave called', 'entity_crud_hook_test_entity_presave called for type taxonomy_vocabulary', 'entity_crud_hook_test_taxonomy_vocabulary_update called', 'entity_crud_hook_test_entity_update called for type taxonomy_vocabulary')); $GLOBALS['entity_crud_hook_test'] = array(); $vocabulary->delete(); $this->assertHookMessageOrder(array('entity_crud_hook_test_taxonomy_vocabulary_predelete called', 'entity_crud_hook_test_entity_predelete called for type taxonomy_vocabulary', 'entity_crud_hook_test_taxonomy_vocabulary_delete called', 'entity_crud_hook_test_entity_delete called for type taxonomy_vocabulary')); }