Skip to content

Cardinality and unlimited

#cardinality is the maximum number of rows. Here the limit is five and two rows exist, plus one empty row.

$form['emails'] = [
'#type' => 'element_multiple',
'#title' => $this->t('Email addresses'),
'#cardinality' => 5,
'#element' => [
'#type' => 'email',
'#title' => $this->t('Email address'),
'#title_display' => 'invisible',
'#placeholder' => $this->t('Enter email address'),
],
'#default_value' => ['example@example.com', 'test@test.com'],
];

A list of two email rows and one empty row, with the Add more control below. The list can still take two more rows.

When the limit is reached, the plus buttons and the “Add more” control disappear. The picture shows the list after typing 3 and clicking Add.

The same list with five rows. Only the minus buttons are left, and the Add more control is gone.

The default is no limit. You can say it with the constant. FALSE means the same.

use Drupal\element_multiple\Element\ElementMultiple;
$form['links'] = [
'#type' => 'element_multiple',
'#title' => $this->t('Links'),
'#cardinality' => ElementMultiple::CARDINALITY_UNLIMITED,
'#element' => [
'#type' => 'url',
'#title' => $this->t('Link'),
'#title_display' => 'invisible',
'#placeholder' => $this->t('Enter link'),
],
'#default_value' => ['https://example.com', 'https://example.org'],
];

A list of two links and one empty row, with the Add more control below. There is no limit.

Even an unlimited list stops at #max_items, which is 1000 by default. This protects the site from requests that ask for millions of rows.

$form['links']['#max_items'] = 200;