function MultipleWidgetFormTest::testFieldFormMultipleWidget

Same name and namespace in other branches
  1. 11.x core/modules/field/tests/src/Functional/MultipleWidgetFormTest.php \Drupal\Tests\field\Functional\MultipleWidgetFormTest::testFieldFormMultipleWidget()

Tests widgets handling multiple values.

File

core/modules/field/tests/src/Functional/MultipleWidgetFormTest.php, line 89

Class

MultipleWidgetFormTest
Tests field form handling.

Namespace

Drupal\Tests\field\Functional

Code

public function testFieldFormMultipleWidget() : void {
  // Create a field with fixed cardinality, configure the form to use a
  // "multiple" widget.
  $field_storage = $this->fieldStorageMultiple;
  $field_name = $field_storage['field_name'];
  $this->field['field_name'] = $field_name;
  FieldStorageConfig::create($field_storage)->save();
  FieldConfig::create($this->field)
    ->save();
  $form = \Drupal::service('entity_display.repository')->getFormDisplay($this->field['entity_type'], $this->field['bundle'], 'default')
    ->setComponent($field_name, [
    'type' => 'test_field_widget_multiple',
  ]);
  $form->save();
  $session = $this->assertSession();
  // Display creation form.
  $this->drupalGet('entity_test/add');
  $this->assertSession()
    ->fieldValueEquals($field_name, '');
  // Create entity with three values.
  $edit = [
    $field_name => '1, 2, 3',
  ];
  $this->submitForm($edit, 'Save');
  preg_match('|entity_test/manage/(\\d+)|', $this->getUrl(), $match);
  $id = $match[1];
  // Check that the values were saved.
  $entity_init = EntityTest::load($id);
  $this->assertFieldValues($entity_init, $field_name, [
    1,
    2,
    3,
  ]);
  // Display the form, check that the values are correctly filled in.
  $this->drupalGet('entity_test/manage/' . $id . '/edit');
  $this->assertSession()
    ->fieldValueEquals($field_name, '1, 2, 3');
  // Submit the form with more values than the field accepts.
  $edit = [
    $field_name => '1, 2, 3, 4, 5',
  ];
  $this->submitForm($edit, 'Save');
  $this->assertSession()
    ->pageTextContains('this field cannot hold more than 4 values');
  // Check that the field values were not submitted.
  $this->assertFieldValues($entity_init, $field_name, [
    1,
    2,
    3,
  ]);
  // Check that Attributes are rendered on the multivalue container if it is
  // a multiple widget form.
  $form->setComponent($field_name, [
    'type' => 'entity_reference_autocomplete',
  ])
    ->save();
  $this->drupalGet('entity_test/manage/' . $id . '/edit');
  $name = str_replace('_', '-', $field_name);
  $session->responseContains('data-drupal-selector="edit-' . $name . '"');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.