Problem
The \Drupal\multivalue_form_element\Element\MultiValue class always renders one extra item due to the following loop condition in MultiValue.php:
for ($i = 0; $i <= $max; $i++) {
This leads to an unnecessary extra (often empty) item being shown, even when a fixed cardinality or default values are used. It also causes issues when rendering the multivalue element manually.
Proposed resolution
Two new optional parameters have been introduced to improve flexibility and preserve backward compatibility:
1. #strict_cardinality
A new element property that allows enforcing exact cardinality without rendering an extra empty item:
'#strict_cardinality' => TRUE
When set to TRUE, the loop condition becomes:
for ($i = 0; $i < $max; $i++) {
This ensures exactly $cardinality items are rendered, without adding an additional empty row.
Default is FALSE to preserve current behavior.
2. #manual_render
A second optional property that signals that all deltas ([0], [1], etc.) are manually rendered outside of the MultiValue processor:
'#manual_render' => TRUEWhen enabled:
- The processor uses manually defined child elements per delta, if available
- Falls back to the previous delta's structure if not explicitly defined
- Disables default cloning of a shared child structure
This is useful for custom dynamic forms with non-uniform or externally built deltas.
Updated loop logic:
if ($manual_render) { $element[$i] = $children[$i] ?? ($element[$i - 1] ?? []); } else { $element[$i] = $children; }
Example usage
$form['banners'] = [ '#type' => 'multivalue', '#cardinality' => 3, '#strict_cardinality' => TRUE, '#manual_render' => TRUE, 0 => ['title' => ['#type' => 'textfield']], 1 => ['title' => ['#type' => 'textfield']], 2 => ['title' => ['#type' => 'textfield']], ];
Issue fork multivalue_form_element-3538710
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #3
rurik666 commentedComment #4
rurik666 commentedComment #5
darvanenThere are some CI failures.