You are here

public function EntityReferenceAutoCreateTest::testNoBundles in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/field/tests/src/Functional/EntityReference/EntityReferenceAutoCreateTest.php \Drupal\Tests\field\Functional\EntityReference\EntityReferenceAutoCreateTest::testNoBundles()

Tests autocreation for an entity that has no bundles.

File

core/modules/field/tests/src/Functional/EntityReference/EntityReferenceAutoCreateTest.php, line 243

Class

EntityReferenceAutoCreateTest
Tests creating new entity (e.g. taxonomy-term) from an autocomplete widget.

Namespace

Drupal\Tests\field\Functional\EntityReference

Code

public function testNoBundles() {
  $account = $this
    ->drupalCreateUser([
    'access content',
    "create {$this->referencingType} content",
    'administer entity_test content',
  ]);
  $this
    ->drupalLogin($account);
  $field_name = mb_strtolower($this
    ->randomMachineName());
  $handler_settings = [
    'auto_create' => TRUE,
  ];
  $this
    ->createEntityReferenceField('node', $this->referencingType, $field_name, $this
    ->randomString(), 'entity_test_no_bundle_with_label', 'default', $handler_settings);
  \Drupal::service('entity_display.repository')
    ->getFormDisplay('node', $this->referencingType)
    ->setComponent($field_name, [
    'type' => 'entity_reference_autocomplete',
  ])
    ->save();
  $node_title = $this
    ->randomMachineName();
  $name = $this
    ->randomMachineName();
  $edit = [
    $field_name . '[0][target_id]' => $name,
    'title[0][value]' => $node_title,
  ];
  $this
    ->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');

  // Assert referenced entity was created.
  $result = \Drupal::entityQuery('entity_test_no_bundle_with_label')
    ->condition('name', $name)
    ->execute();
  $this
    ->assertNotEmpty($result, 'Referenced entity was created.');
  $referenced_id = key($result);

  // Assert the referenced entity is associated with referencing node.
  $result = \Drupal::entityQuery('node')
    ->condition('type', $this->referencingType)
    ->execute();
  $this
    ->assertCount(1, $result);
  $referencing_nid = key($result);
  $referencing_node = Node::load($referencing_nid);
  $this
    ->assertEqual($referenced_id, $referencing_node->{$field_name}->target_id, 'Newly created node is referenced from the referencing entity.');
}