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(); }
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'); }
/** * 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.'); }
/** * {@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; }
/** * {@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 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'); }
/** * 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.'); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); Vocabulary::create(['vid' => 'tags', 'name' => 'Tags'])->save(); // Setup a hierarchy which looks like this: // term 0.0 // term 1.0 // - term 1.1 // term 2.0 // - term 2.1 // - term 2.2 for ($i = 0; $i < 3; $i++) { for ($j = 0; $j <= $i; $j++) { $this->terms[$i][$j] = $term = Term::create(['vid' => 'tags', 'name' => "Term {$i}.{$j}", 'parent' => isset($terms[$i][0]) ? $terms[$i][0]->id() : 0]); $term->save(); } } ViewTestData::createTestViews(get_class($this), array('taxonomy_test_views')); }
/** * 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()); }
/** * 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); }
/** * 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 the forum validation constraints. */ public function testValidation() { // Add a forum. $forum = Term::create(['name' => 'forum 1', 'vid' => 'forums', 'forum_container' => 0]); // Add a container. $container = Term::create(['name' => 'container 1', 'vid' => 'forums', 'forum_container' => 1]); // Add a forum post. $forum_post = Node::create(['type' => 'forum', 'title' => 'Do these pants make my butt look big?']); $violations = $forum_post->validate(); $this->assertEqual(count($violations), 1); $this->assertEqual($violations[0]->getMessage(), 'This value should not be null.'); // Add the forum term. $forum_post->set('taxonomy_forums', $forum); $violations = $forum_post->validate(); $this->assertEqual(count($violations), 0); // Try to use a container. $forum_post->set('taxonomy_forums', $container); $violations = $forum_post->validate(); $this->assertEqual(count($violations), 1); $this->assertEqual($violations[0]->getMessage(), t('The item %forum is a forum container, not a forum. Select one of the forums below instead.', ['%forum' => $container->label()])); }
public function testTitleOptionsFromTaxonomy() { $field = $this->createNameField('field_name_test', 'entity_test', 'entity_test'); $vocabulary = Vocabulary::create(array('vid' => 'title_options', 'name' => 'Title options')); $vocabulary->save(); foreach (array('foo', 'bar', 'baz') as $name) { $term = Term::create(array('name' => $name, 'vid' => $vocabulary->id())); $term->save(); } /** * @var \Drupal\field\Entity\FieldStorageConfig $field_storage */ $field_storage = $field->getFieldStorageDefinition(); $settings = $field_storage->getSettings(); $settings['title_options'] = array('-- --', '[vocabulary:title_options]'); $settings['sort_options']['title'] = TRUE; $field_storage->set('settings', $settings); $field_storage->save(); $expected = array('' => '--', 'bar' => 'bar', 'baz' => 'baz', 'foo' => 'foo'); $this->assertEqual($expected, $this->optionsProvider->getOptions($field, 'title')); }
protected function setUp() { parent::setUp(); // Install all available non-testing themes. $listing = new ExtensionDiscovery(\Drupal::root()); $this->themes = $listing->scan('theme', FALSE); \Drupal::service('theme_handler')->install(array_keys($this->themes)); // Create a test user. $this->user = $this->drupalCreateUser(array('access content', 'access user profiles')); $this->user->name = $this->xssLabel; $this->user->save(); $this->drupalLogin($this->user); // Create a test term. $this->term = Term::create(['name' => $this->xssLabel, 'vid' => 1]); $this->term->save(); // Add a comment field. $this->addDefaultCommentField('node', 'article', 'comment', CommentItemInterface::OPEN); // Create a test node tagged with the test term. $this->node = $this->drupalCreateNode(array('title' => $this->xssLabel, 'type' => 'article', 'promote' => NODE_PROMOTED, 'field_tags' => array(array('target_id' => $this->term->id())))); // Create a test comment on the test node. $this->comment = Comment::create(array('entity_id' => $this->node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'status' => CommentInterface::PUBLISHED, 'subject' => $this->xssLabel, 'comment_body' => array($this->randomMachineName()))); $this->comment->save(); }
/** * Tests that the taxonomy index work correctly with forward revisions. */ public function testTaxonomyIndexWithForwardRevision() { \Drupal::configFactory()->getEditable('taxonomy.settings')->set('maintain_index_table', TRUE)->save(); Vocabulary::create(['name' => 'test', 'vid' => 'test'])->save(); $term = Term::create(['name' => 'term1', 'vid' => 'test']); $term->save(); $term2 = Term::create(['name' => 'term2', 'vid' => 'test']); $term2->save(); NodeType::create(['type' => 'page'])->save(); FieldStorageConfig::create(['entity_type' => 'node', 'field_name' => 'field_tags', 'type' => 'entity_reference', 'settings' => ['target_type' => 'taxonomy_term']])->save(); FieldConfig::create(['field_name' => 'field_tags', 'entity_type' => 'node', 'bundle' => 'page'])->save(); $node = Node::create(['type' => 'page', 'title' => 'test_title', 'field_tags' => [$term->id()]]); $node->save(); $taxonomy_index = $this->getTaxonomyIndex(); $this->assertEquals($term->id(), $taxonomy_index[$node->id()]->tid); // Normal new revision. $node->setNewRevision(TRUE); $node->isDefaultRevision(TRUE); $node->field_tags->target_id = $term2->id(); $node->save(); $taxonomy_index = $this->getTaxonomyIndex(); $this->assertEquals($term2->id(), $taxonomy_index[$node->id()]->tid); // Check that saving a forward (non-default) revision does not affect the // taxonomy index. $node->setNewRevision(TRUE); $node->isDefaultRevision(FALSE); $node->field_tags->target_id = $term->id(); $node->save(); $taxonomy_index = $this->getTaxonomyIndex(); $this->assertEquals($term2->id(), $taxonomy_index[$node->id()]->tid); // Check that making the previously created forward-revision the default // revision updates the taxonomy index correctly. $node->isDefaultRevision(TRUE); $node->save(); $taxonomy_index = $this->getTaxonomyIndex(); $this->assertEquals($term->id(), $taxonomy_index[$node->id()]->tid); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installSchema('system', array('sequences')); $this->installEntitySchema('node'); $this->installEntitySchema('user'); $this->installEntitySchema('taxonomy_term'); NodeType::create(['type' => 'page', 'name' => 'Basic page', 'display_submitted' => FALSE])->save(); // 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(); // Add a term to the vocabulary. $this->term = Term::create(['name' => 'Sometimes people are just jerks', 'description' => $this->randomMachineName(), 'vid' => $vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED]); $this->term->save(); // Create a field. $handler_settings = array('target_bundles' => array($vocabulary->id() => $vocabulary->id()), 'auto_create' => TRUE); // Add the term field. FieldStorageConfig::create(array('field_name' => 'field_term', 'type' => 'entity_reference', 'entity_type' => 'node', 'cardinality' => 1, 'settings' => array('target_type' => 'taxonomy_term')))->save(); FieldConfig::create(array('field_name' => 'field_term', 'entity_type' => 'node', 'bundle' => 'page', 'label' => 'Terms', 'settings' => array('handler' => 'default', 'handler_settings' => $handler_settings)))->save(); // Show on default display and teaser. entity_get_display('node', 'page', 'default')->setComponent('field_term', array('type' => 'entity_reference_label'))->save(); // Boot twig environment. $this->twig = \Drupal::service('twig'); }
/** * Creates a taxonomy term with specified name and other properties. * * @param array $properties * Array of properties and field values to set. * * @return \Drupal\taxonomy\TermInterface * The created taxonomy term. */ protected function createTermWithProperties($properties) { // Use the first available text format. $filter_formats = filter_formats(); $format = array_pop($filter_formats); $properties += array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'field_foo' => $this->randomMachineName()); $term = Term::create(['name' => $properties['name'], 'description' => $properties['description'], 'format' => $format->id(), 'vid' => $this->vocabulary->id(), 'langcode' => $properties['langcode']]); $term->field_foo->value = $properties['field_foo']; $term->save(); return $term; }
/** * Test using fields for path structures. */ function testParentChildPathTokens() { // First create a field which will be used to create the path. It must // begin with a letter. $this->installEntitySchema('taxonomy_term'); Vocabulary::create(['vid' => 'tags'])->save(); $fieldname = 'a' . Unicode::strtolower($this->randomMachineName()); $field_storage = FieldStorageConfig::create(['entity_type' => 'taxonomy_term', 'field_name' => $fieldname, 'type' => 'string']); $field_storage->save(); $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'tags']); $field->save(); $display = entity_get_display('taxonomy_term', 'tags', 'default'); $display->setComponent($fieldname, ['type' => 'string']); $display->save(); // Make the path pattern of a field use the value of this field appended // to the parent taxonomy term's pattern if there is one. $config = $this->config('pathauto.pattern'); $config->set('patterns.taxonomy_term.default', '/[term:parents:join-path]/[term:' . $fieldname . ']'); $config->save(); // Start by creating a parent term. $parent = Term::create(['vid' => 'tags', $fieldname => $this->randomMachineName(), 'name' => $this->randomMachineName()]); $parent->save(); // Create the child term. $child = Term::create(['vid' => 'tags', $fieldname => $this->randomMachineName(), 'parent' => $parent, 'name' => $this->randomMachineName()]); $child->save(); $this->assertEntityAlias($child, '/' . Unicode::strtolower($parent->getName() . '/' . $child->{$fieldname}->value)); // Re-saving the parent term should not modify the child term's alias. $parent->save(); $this->assertEntityAlias($child, '/' . Unicode::strtolower($parent->getName() . '/' . $child->{$fieldname}->value)); }
/** * Creates a taxonomy term of a given vocabulary. * * It uses $this->field_names to populate content of attached fields. You can * access fields values using * $this->field_names['taxonomy_term'][$vocabulary->id(]. * * @param object $vocabulary * Vocabulary object for which the term should be created. * * @return object * Newly created node object. */ function createTaxonomyTerm(VocabularyInterface $vocabulary) { $term = Term::create(array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $vocabulary->id(), 'langcode' => 'en')); foreach ($this->field_names['taxonomy_term'][$vocabulary->id()] as $field_name) { $field_definition = $term->getFieldDefinition($field_name); $cardinality = $field_definition->getFieldStorageDefinition()->getCardinality() == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED ? 1 : $field_definition->getCardinality(); $field_lang = $field_definition->isTranslatable() ? 'en' : LanguageInterface::LANGCODE_DEFAULT; // Create two deltas for each field. for ($delta = 0; $delta <= $cardinality; $delta++) { $term->getTranslation($field_lang)->get($field_name)->get($delta)->value = $this->randomMachineName(20); if ($field_definition->getType() == 'text_with_summary') { $term->getTranslation($field_lang)->get($field_name)->get($delta)->summary = $this->randomMachineName(10); } } } $term->save(); return $term; }
/** * 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()); }
protected function setUp() { parent::setUp(); // Use Classy theme for testing markup output. \Drupal::service('theme_handler')->install(['classy']); \Drupal::service('theme_handler')->setDefault('classy'); $this->baseUri = \Drupal::url('<front>', [], ['absolute' => TRUE]); // Create two test users. $this->adminUser = $this->drupalCreateUser(array('administer content types', 'administer comments', 'access comments', 'access content')); $this->webUser = $this->drupalCreateUser(array('access comments', 'post comments', 'skip comment approval', 'access content')); $this->drupalLogin($this->adminUser); // Create term. $this->term = Term::create(['name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => 'tags']); $this->term->save(); // Create image. file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example.jpg'); $this->image = File::create(['uri' => 'public://example.jpg']); $this->image->save(); // Create article. $article_settings = array('type' => 'article', 'promote' => NODE_PROMOTED, 'field_image' => array(array('target_id' => $this->image->id())), 'field_tags' => array(array('target_id' => $this->term->id()))); $this->article = $this->drupalCreateNode($article_settings); // Create second article to test teaser list. $this->drupalCreateNode(array('type' => 'article', 'promote' => NODE_PROMOTED)); // Create article comment. $this->articleComment = $this->saveComment($this->article->id(), $this->webUser->id(), NULL, 0); // Create page. $this->page = $this->drupalCreateNode(array('type' => 'page')); // Set URIs. // Image. $image_file = $this->article->get('field_image')->entity; $this->imageUri = ImageStyle::load('large')->buildUrl($image_file->getFileUri()); // Term. $this->termUri = $this->term->url('canonical', array('absolute' => TRUE)); // Article. $this->articleUri = $this->article->url('canonical', array('absolute' => TRUE)); // Page. $this->pageUri = $this->page->url('canonical', array('absolute' => TRUE)); // Author. $this->authorUri = $this->adminUser->url('canonical', array('absolute' => TRUE)); // Comment. $this->articleCommentUri = $this->articleComment->url('canonical', array('absolute' => TRUE)); // Commenter. $this->commenterUri = $this->webUser->url('canonical', array('absolute' => TRUE)); $this->drupalLogout(); }
/** * Test base fields with multiple columns. */ public function testBaseFieldMultipleColumns() { $this->enableModules(['taxonomy']); $this->installEntitySchema('taxonomy_term'); Vocabulary::create(['vid' => 'tags']); $term1 = Term::create(['name' => $this->randomMachineName(), 'vid' => 'tags', 'description' => array('value' => $this->randomString(), 'format' => 'format1')]); $term1->save(); $term2 = Term::create(['name' => $this->randomMachineName(), 'vid' => 'tags', 'description' => array('value' => $this->randomString(), 'format' => 'format2')]); $term2->save(); $ids = \Drupal::entityQuery('taxonomy_term')->condition('description.format', 'format1')->execute(); $this->assertEqual(count($ids), 1); $this->assertEqual($term1->id(), reset($ids)); }
/** * Test taxonomy_term_load_multiple_by_name(). */ function testTaxonomyGetTermByName() { $term = $this->createTerm($this->vocabulary); // Load the term with the exact name. $terms = taxonomy_term_load_multiple_by_name($term->getName()); $this->assertTrue(isset($terms[$term->id()]), 'Term loaded using exact name.'); // Load the term with space concatenated. $terms = taxonomy_term_load_multiple_by_name(' ' . $term->getName() . ' '); $this->assertTrue(isset($terms[$term->id()]), 'Term loaded with extra whitespace.'); // Load the term with name uppercased. $terms = taxonomy_term_load_multiple_by_name(strtoupper($term->getName())); $this->assertTrue(isset($terms[$term->id()]), 'Term loaded with uppercased name.'); // Load the term with name lowercased. $terms = taxonomy_term_load_multiple_by_name(strtolower($term->getName())); $this->assertTrue(isset($terms[$term->id()]), 'Term loaded with lowercased name.'); // Try to load an invalid term name. $terms = taxonomy_term_load_multiple_by_name('Banana'); $this->assertFalse($terms, 'No term loaded with an invalid name.'); // Try to load the term using a substring of the name. $terms = taxonomy_term_load_multiple_by_name(Unicode::substr($term->getName(), 2), 'No term loaded with a substring of the name.'); $this->assertFalse($terms); // Create a new term in a different vocabulary with the same name. $new_vocabulary = $this->createVocabulary(); $new_term = Term::create(['name' => $term->getName(), 'vid' => $new_vocabulary->id()]); $new_term->save(); // Load multiple terms with the same name. $terms = taxonomy_term_load_multiple_by_name($term->getName()); $this->assertEqual(count($terms), 2, 'Two terms loaded with the same name.'); // Load single term when restricted to one vocabulary. $terms = taxonomy_term_load_multiple_by_name($term->getName(), $this->vocabulary->id()); $this->assertEqual(count($terms), 1, 'One term loaded when restricted by vocabulary.'); $this->assertTrue(isset($terms[$term->id()]), 'Term loaded using exact name and vocabulary machine name.'); // Create a new term with another name. $term2 = $this->createTerm($this->vocabulary); // Try to load a term by name that doesn't exist in this vocabulary but // exists in another vocabulary. $terms = taxonomy_term_load_multiple_by_name($term2->getName(), $new_vocabulary->id()); $this->assertFalse($terms, 'Invalid term name restricted by vocabulary machine name not loaded.'); // Try to load terms filtering by a non-existing vocabulary. $terms = taxonomy_term_load_multiple_by_name($term2->getName(), 'non_existing_vocabulary'); $this->assertEqual(count($terms), 0, 'No terms loaded when restricted by a non-existing vocabulary.'); }
/** * {@inheritDoc} */ public function termCreate(\stdClass $term) { $term->vid = $term->vocabulary_machine_name; $entity = Term::create((array) $term); $entity->save(); $term->tid = $entity->id(); return $term; }
/** * 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])); } }
/** * Tests validation constraint. */ public function testValidation() { // The term entity is unsaved here. $term = Term::create(array('name' => $this->randomMachineName(), 'vid' => $this->term->bundle(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $entity = EntityTest::create(['field_test_taxonomy_term' => ['entity' => $term, 'target_id' => NULL]]); $errors = $entity->validate(); // Using target_id of NULL is valid with an unsaved entity. $this->assertEqual(0, count($errors)); // Using target_id of NULL is not valid with a saved entity. $term->save(); $entity = EntityTest::create(['field_test_taxonomy_term' => ['entity' => $term, 'target_id' => NULL]]); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), 'This value should not be null.'); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_taxonomy_term.0'); // This should rectify the issue, favoring the entity over the target_id. $entity->save(); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); }
/** * Tests ValidReferenceConstraint with newly created and unsaved entities. */ public function testAutocreateValidation() { // The term entity is unsaved here. $term = Term::create(array('name' => $this->randomMachineName(), 'vid' => $this->term->bundle(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $entity = EntityTest::create(['field_test_taxonomy_term' => ['entity' => $term, 'target_id' => NULL]]); $errors = $entity->validate(); // Using target_id of NULL is valid with an unsaved entity. $this->assertEqual(0, count($errors)); // Using target_id of NULL is not valid with a saved entity. $term->save(); $entity = EntityTest::create(['field_test_taxonomy_term' => ['entity' => $term, 'target_id' => NULL]]); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), 'This value should not be null.'); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_taxonomy_term.0'); // This should rectify the issue, favoring the entity over the target_id. $entity->save(); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); // Test with an unpublished and unsaved node. $title = $this->randomString(); $node = Node::create(['title' => $title, 'type' => 'node', 'status' => NODE_NOT_PUBLISHED]); $entity = EntityTest::create(['field_test_node' => ['entity' => $node]]); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $title])); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity'); // Publish the node and try again. $node->setPublished(TRUE); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); // Test with a mix of valid and invalid nodes. $unsaved_unpublished_node_title = $this->randomString(); $unsaved_unpublished_node = Node::create(['title' => $unsaved_unpublished_node_title, 'type' => 'node', 'status' => NODE_NOT_PUBLISHED]); $saved_unpublished_node_title = $this->randomString(); $saved_unpublished_node = Node::create(['title' => $saved_unpublished_node_title, 'type' => 'node', 'status' => NODE_NOT_PUBLISHED]); $saved_unpublished_node->save(); $saved_published_node_title = $this->randomString(); $saved_published_node = Node::create(['title' => $saved_published_node_title, 'type' => 'node', 'status' => NODE_PUBLISHED]); $saved_published_node->save(); $entity = EntityTest::create(['field_test_node' => [['entity' => $unsaved_unpublished_node], ['target_id' => $saved_unpublished_node->id()], ['target_id' => $saved_published_node->id()]]]); $errors = $entity->validate(); $this->assertEqual(2, count($errors)); $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title])); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity'); $this->assertEqual($errors[1]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $saved_unpublished_node->id()])); $this->assertEqual($errors[1]->getPropertyPath(), 'field_test_node.1.target_id'); // Publish one of the nodes and try again. $saved_unpublished_node->setPublished(TRUE); $saved_unpublished_node->save(); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title])); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity'); // Publish the last invalid node and try again. $unsaved_unpublished_node->setPublished(TRUE); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); // Test with an unpublished and unsaved comment. $title = $this->randomString(); $comment = Comment::create(['subject' => $title, 'comment_type' => 'comment', 'status' => 0]); $entity = EntityTest::create(['field_test_comment' => ['entity' => $comment]]); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'comment', '%label' => $title])); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_comment.0.entity'); // Publish the comment and try again. $comment->setPublished(TRUE); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); // Test with an inactive and unsaved user. $name = $this->randomString(); $user = User::create(['name' => $name, 'status' => 0]); $entity = EntityTest::create(['field_test_user' => ['entity' => $user]]); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'user', '%label' => $name])); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_user.0.entity'); // Activate the user and try again. $user->activate(); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); // Test with a temporary and unsaved file. $filename = $this->randomMachineName() . '.txt'; $file = File::create(['filename' => $filename, 'status' => 0]); $entity = EntityTest::create(['field_test_file' => ['entity' => $file]]); $errors = $entity->validate(); $this->assertEqual(1, count($errors)); $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'file', '%label' => $filename])); $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_file.0.entity'); // Set the file as permanent and try again. $file->setPermanent(); $errors = $entity->validate(); $this->assertEqual(0, count($errors)); }
/** * {@inheritdoc} */ public function termCreate(\stdClass $term) { $term->vid = $term->vocabulary_machine_name; $this->expandEntityFields('taxonomy_term', $term); $entity = Term::create((array) $term); $entity->save(); $term->tid = $entity->id(); return $term; }
/** * Takes array of category names, creates the Drupal term if needed, returns Drupal tax term ids. * * @param array $name_array Array of category names (strings) * * @return array $cat_id_array Array of Drupal Tax term ids for individual article. */ public function load_tax_terms($name_array) { $loop_section = $this->errors->get_section(); $this->errors->set_section('Load tax terms'); $vocab = 'brafton_tax'; $cat_id_array = array(); foreach ($name_array as $name) { $existing_terms = taxonomy_term_load_multiple_by_name($name, $vocab); // If term does not exist, create it. if (empty($existing_terms)) { // Creates new taxonomy term. $tax_info = array('name' => $name, 'vid' => $vocab); $brafton_tax_term = \Drupal\taxonomy\Entity\Term::create($tax_info); $brafton_tax_term->save(); $term_vid = $brafton_tax_term->id(); } else { $term_vid = reset($existing_terms)->id(); } $cat_id_array[] = $term_vid; } // returns array of unique term ids (vid). $this->errors->set_section($loop_section); return $cat_id_array; }