EntityReferenceAutoCreateTest.php 10.1 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\field\Functional\EntityReference;
4

5
use Drupal\Core\Field\FieldStorageDefinitionInterface;
6
use Drupal\field\Entity\FieldConfig;
7
use Drupal\Tests\BrowserTestBase;
8
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
9
use Drupal\taxonomy\Entity\Vocabulary;
10
use Drupal\node\Entity\Node;
11
use Drupal\field\Entity\FieldStorageConfig;
12 13

/**
14 15 16
 * Tests creating new entity (e.g. taxonomy-term) from an autocomplete widget.
 *
 * @group entity_reference
17
 */
18
class EntityReferenceAutoCreateTest extends BrowserTestBase {
19

20 21
  use EntityReferenceTestTrait;

22
  protected static $modules = ['node', 'taxonomy', 'entity_test'];
23

24 25 26 27 28
  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

29 30 31 32 33 34 35 36 37 38 39 40 41 42
  /**
   * The name of a content type that will reference $referencedType.
   *
   * @var string
   */
  protected $referencingType;

  /**
   * The name of a content type that will be referenced by $referencingType.
   *
   * @var string
   */
  protected $referencedType;

43
  protected function setUp(): void {
44 45 46 47
    parent::setUp();

    // Create "referencing" and "referenced" node types.
    $referencing = $this->drupalCreateContentType();
48
    $this->referencingType = $referencing->id();
49 50

    $referenced = $this->drupalCreateContentType();
51
    $this->referencedType = $referenced->id();
52

53
    FieldStorageConfig::create([
54
      'field_name' => 'test_field',
55
      'entity_type' => 'node',
56
      'translatable' => FALSE,
57 58
      'entity_types' => [],
      'settings' => [
59
        'target_type' => 'node',
60
      ],
61
      'type' => 'entity_reference',
62
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
63
    ])->save();
64

65
    FieldConfig::create([
66 67 68
      'label' => 'Entity reference field',
      'field_name' => 'test_field',
      'entity_type' => 'node',
69
      'bundle' => $referencing->id(),
70
      'settings' => [
71
        'handler' => 'default',
72
        'handler_settings' => [
73
          // Reference a single vocabulary.
74
          'target_bundles' => [
75
            $referenced->id(),
76
          ],
77 78
          // Enable auto-create.
          'auto_create' => TRUE,
79 80
        ],
      ],
81
    ])->save();
82

83 84 85 86
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');

    $display_repository->getViewDisplay('node', $referencing->id())
87 88
      ->setComponent('test_field')
      ->save();
89
    $display_repository->getFormDisplay('node', $referencing->id(), 'default')
90
      ->setComponent('test_field', [
91
        'type' => 'entity_reference_autocomplete',
92
      ])
93
      ->save();
94

95 96 97 98
    $account = $this->drupalCreateUser([
      'access content',
      "create $this->referencingType content",
    ]);
99
    $this->drupalLogin($account);
100 101 102
  }

  /**
103 104
   * Tests that the autocomplete input element appears and the creation of a new
   * entity.
105 106
   */
  public function testAutoCreate() {
107
    $this->drupalGet('node/add/' . $this->referencingType);
108 109
    $target = $this->assertSession()->fieldExists("edit-test-field-0-target-id");
    $this->assertTrue($target->hasClass("form-autocomplete"));
110

111
    $new_title = $this->randomMachineName();
112 113

    // Assert referenced node does not exist.
114
    $base_query = \Drupal::entityQuery('node');
115
    $base_query
116
      ->condition('type', $this->referencedType)
117 118 119 120
      ->condition('title', $new_title);

    $query = clone $base_query;
    $result = $query->execute();
121
    $this->assertEmpty($result, 'Referenced node does not exist yet.');
122

123
    $edit = [
124
      'title[0][value]' => $this->randomMachineName(),
125
      'test_field[0][target_id]' => $new_title,
126
    ];
127
    $this->drupalPostForm("node/add/$this->referencingType", $edit, 'Save');
128 129 130 131

    // Assert referenced node was created.
    $query = clone $base_query;
    $result = $query->execute();
132
    $this->assertNotEmpty($result, 'Referenced node was created.');
133
    $referenced_nid = key($result);
134
    $referenced_node = Node::load($referenced_nid);
135 136

    // Assert the referenced node is associated with referencing node.
137
    $result = \Drupal::entityQuery('node')
138
      ->condition('type', $this->referencingType)
139 140 141
      ->execute();

    $referencing_nid = key($result);
142
    $referencing_node = Node::load($referencing_nid);
143
    $this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
144 145 146 147 148

    // Now try to view the node and check that the referenced node is shown.
    $this->drupalGet('node/' . $referencing_node->id());
    $this->assertText($referencing_node->label(), 'Referencing node label found.');
    $this->assertText($referenced_node->label(), 'Referenced node label found.');
149
  }
150 151 152 153 154 155 156 157 158

  /**
   * Tests if an entity reference field having multiple target bundles is
   * storing the auto-created entity in the right destination.
   */
  public function testMultipleTargetBundles() {
    /** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
    $vocabularies = [];
    for ($i = 0; $i < 2; $i++) {
159
      $vid = mb_strtolower($this->randomMachineName());
160 161 162 163 164 165 166 167 168 169
      $vocabularies[$i] = Vocabulary::create([
        'name' => $this->randomMachineName(),
        'vid' => $vid,
      ]);
      $vocabularies[$i]->save();
    }

    // Create a taxonomy term entity reference field that saves the auto-created
    // taxonomy terms in the second vocabulary from the two that were configured
    // as targets.
170
    $field_name = mb_strtolower($this->randomMachineName());
171 172 173 174 175 176 177 178 179 180
    $handler_settings = [
      'target_bundles' => [
        $vocabularies[0]->id() => $vocabularies[0]->id(),
        $vocabularies[1]->id() => $vocabularies[1]->id(),
      ],
      'auto_create' => TRUE,
      'auto_create_bundle' => $vocabularies[1]->id(),
    ];
    $this->createEntityReferenceField('node', $this->referencingType, $field_name, $this->randomString(), 'taxonomy_term', 'default', $handler_settings);
    /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $fd */
181 182
    \Drupal::service('entity_display.repository')
      ->getFormDisplay('node', $this->referencingType)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
      ->setComponent($field_name, ['type' => 'entity_reference_autocomplete'])
      ->save();

    $term_name = $this->randomString();
    $edit = [
      $field_name . '[0][target_id]' => $term_name,
      'title[0][value]' => $this->randomString(),
    ];

    $this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');
    /** @var \Drupal\taxonomy\Entity\Term $term */
    $term = taxonomy_term_load_multiple_by_name($term_name);
    $term = reset($term);

    // The new term is expected to be stored in the second vocabulary.
    $this->assertEqual($vocabularies[1]->id(), $term->bundle());

    /** @var \Drupal\field\Entity\FieldConfig $field_config */
    $field_config = FieldConfig::loadByName('node', $this->referencingType, $field_name);
    $handler_settings = $field_config->getSetting('handler_settings');

    // Change the field setting to store the auto-created terms in the first
    // vocabulary and test again.
    $handler_settings['auto_create_bundle'] = $vocabularies[0]->id();
    $field_config->setSetting('handler_settings', $handler_settings);
    $field_config->save();

    $term_name = $this->randomString();
    $edit = [
      $field_name . '[0][target_id]' => $term_name,
      'title[0][value]' => $this->randomString(),
    ];

    $this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');
    /** @var \Drupal\taxonomy\Entity\Term $term */
    $term = taxonomy_term_load_multiple_by_name($term_name);
    $term = reset($term);

    // The second term is expected to be stored in the first vocabulary.
    $this->assertEqual($vocabularies[0]->id(), $term->bundle());

    // @todo Re-enable this test when WebTestBase::curlHeaderCallback() provides
    //   a way to catch and assert user-triggered errors.

    // Test the case when the field config settings are inconsistent.
228 229 230
    // unset($handler_settings['auto_create_bundle']);
    // $field_config->setSetting('handler_settings', $handler_settings);
    // $field_config->save();
231
    //
232 233
    // $this->drupalGet('node/add/' . $this->referencingType);
    // $error_message = sprintf(
234 235 236
    //  "Create referenced entities if they don't already exist option is enabled but a specific destination bundle is not set. You should re-visit and fix the settings of the '%s' (%s) field.",
    //  $field_config->getLabel(),
    //  $field_config->getName()
237 238
    // );
    // $this->assertErrorLogged($error_message);
239 240
  }

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  /**
   * Tests autocreation for an entity that has no bundles.
   */
  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.');
  }

288
}