diff -u b/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldWidget/ShapeOnlyColorEditableWidget.php b/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldWidget/ShapeOnlyColorEditableWidget.php --- b/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldWidget/ShapeOnlyColorEditableWidget.php +++ b/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldWidget/ShapeOnlyColorEditableWidget.php @@ -3,6 +3,7 @@ namespace Drupal\entity_test\Plugin\Field\FieldWidget; use Drupal\Core\Field\FieldItemListInterface; +use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\Core\Field\WidgetBase; use Drupal\Core\Form\FormStateInterface; @@ -39,2 +40,29 @@ + protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state){ + $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality(); + + // Determine the number of widgets to display. + switch ($cardinality) { + case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED: + $field_name = $this->fieldDefinition->getName(); + $parents = $form['#parents']; + + $field_state = static::getWidgetState($parents, $field_name, $form_state); + $max = $field_state['items_count']; + break; + + default: + $max = $cardinality - 1; + break; + } + + for ($delta = 0; $delta <= $max; $delta++) { + // Add a new empty item if it doesn't exist yet at this delta. + if (!isset($items[$delta])) { + $items->appendItem(['shape' => 'circle', 'color' => 'red']); + } + } + + return parent::formMultipleElements($items, $form, $form_state); + } } diff -u b/core/tests/Drupal/FunctionalTests/Entity/EntityFormCorrectUserInputMappingOnFieldDeltaElementsTest.php b/core/tests/Drupal/FunctionalTests/Entity/EntityFormCorrectUserInputMappingOnFieldDeltaElementsTest.php --- b/core/tests/Drupal/FunctionalTests/Entity/EntityFormCorrectUserInputMappingOnFieldDeltaElementsTest.php +++ b/core/tests/Drupal/FunctionalTests/Entity/EntityFormCorrectUserInputMappingOnFieldDeltaElementsTest.php @@ -96,6 +96,10 @@ // mapping will break after the form builder maps over the new form the // user submitted values based on the previous delta ordering. $this->drupalPostForm(NULL, $edit, t('Add another item')); + $this->assertRaw('name="shape[2][shape]" value="circle"'); + $this->assertRaw('name="shape[2][color]" value="red"'); + $this->assertRaw('name="shape[3][shape]" value="circle"'); + $this->assertRaw('name="shape[3][color]" value="red"'); $this->drupalPostForm(NULL, [], t('Save')); // Reload the entity. @@ -106,6 +110,8 @@ $this->assertEquals($entity->get($this->fieldName)->getValue(), [ ['shape' => 'circle', 'color' => 'blue'], ['shape' => 'rectangle', 'color' => 'green'], + ['shape' => 'circle', 'color' => 'red'], + ['shape' => 'circle', 'color' => 'red'], ]); }