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

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

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

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

21 22 23
  use EntityReferenceTestTrait;

  public static $modules = ['node', 'taxonomy'];
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38
  /**
   * 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;

39
  protected function setUp() {
40 41 42 43
    parent::setUp();

    // Create "referencing" and "referenced" node types.
    $referencing = $this->drupalCreateContentType();
44
    $this->referencingType = $referencing->id();
45 46

    $referenced = $this->drupalCreateContentType();
47
    $this->referencedType = $referenced->id();
48

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

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

79
    entity_get_display('node', $referencing->id(), 'default')
80 81
      ->setComponent('test_field')
      ->save();
82
    entity_get_form_display('node', $referencing->id(), 'default')
83
      ->setComponent('test_field', [
84
        'type' => 'entity_reference_autocomplete',
85
      ])
86
      ->save();
87 88 89

    $account = $this->drupalCreateUser(['access content', "create $this->referencingType content"]);
    $this->drupalLogin($account);
90 91 92
  }

  /**
93 94
   * Tests that the autocomplete input element appears and the creation of a new
   * entity.
95 96
   */
  public function testAutoCreate() {
97
    $this->drupalGet('node/add/' . $this->referencingType);
98 99
    $this->assertFieldByXPath('//input[@id="edit-test-field-0-target-id" and contains(@class, "form-autocomplete")]', NULL, 'The autocomplete input element appears.');

100
    $new_title = $this->randomMachineName();
101 102

    // Assert referenced node does not exist.
103
    $base_query = \Drupal::entityQuery('node');
104
    $base_query
105
      ->condition('type', $this->referencedType)
106 107 108 109 110 111
      ->condition('title', $new_title);

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

112
    $edit = [
113
      'title[0][value]' => $this->randomMachineName(),
114
      'test_field[0][target_id]' => $new_title,
115
    ];
116
    $this->drupalPostForm("node/add/$this->referencingType", $edit, 'Save');
117 118 119 120 121 122

    // Assert referenced node was created.
    $query = clone $base_query;
    $result = $query->execute();
    $this->assertTrue($result, 'Referenced node was created.');
    $referenced_nid = key($result);
123
    $referenced_node = Node::load($referenced_nid);
124 125

    // Assert the referenced node is associated with referencing node.
126
    $result = \Drupal::entityQuery('node')
127
      ->condition('type', $this->referencingType)
128 129 130
      ->execute();

    $referencing_nid = key($result);
131
    $referencing_node = Node::load($referencing_nid);
132
    $this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
133 134 135 136 137

    // 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.');
138
  }
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 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

  /**
   * 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++) {
      $vid = Unicode::strtolower($this->randomMachineName());
      $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.
    $field_name = Unicode::strtolower($this->randomMachineName());
    $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 */
    entity_get_form_display('node', $this->referencingType, 'default')
      ->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.
216 217 218
    //unset($handler_settings['auto_create_bundle']);
    //$field_config->setSetting('handler_settings', $handler_settings);
    //$field_config->save();
219
    //
220 221
    //$this->drupalGet('node/add/' . $this->referencingType);
    //$error_message = sprintf(
222 223 224
    //  "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()
225 226
    //);
    //$this->assertErrorLogged($error_message);
227 228
  }

229
}