Repeater: Dynamic Containers

Do you need a form where users can add and remove items themselves? Invoice rows, a list of contacts, multiple e-mail addresses? This is exactly what Repeater is for – a container that can repeat itself.

Repeater is similar to a container, except that you don't define its contents as a fixed set, but as a recipe for a single item. How many items are eventually created is decided by the user in the browser, or by the submitted data.

Basic Usage

We add a repeater to the form using the addRepeater() method. The first parameter is the name, the second is a function that builds one item – it receives an empty container and adds controls to it:

$persons = $form->addRepeater('persons', function (Nette\Forms\Container $person) {
	$person->addText('name', 'Name:')
		->setRequired();
	$person->addEmail('email', 'E-mail:');
});

That's the whole definition. Nette takes care of the rest: based on the submitted data, it creates the corresponding number of items, validates them, and the getValues() method returns the data as an array:

$data = $form->getValues();
// $data->persons contains an array of items
foreach ($data->persons as $person) {
	echo $person->name, ': ', $person->email;
}

We set default values using the setDefaults() method directly on the repeater, one array element per item. The repeater immediately creates the necessary items based on them:

$persons->setDefaults([
	['name' => 'John Doe', 'email' => 'john@example.com'],
	['name' => 'Jane Doe', 'email' => 'jane@example.com'],
]);

And if a control should have the same default value in every new item, set it using the usual setDefaultValue() right in the definition function.

Inside an item, you can use all the usual controls, nested containers, and even other repeaters. Validation rules, conditions, and custom controls work exactly the same as anywhere else in the form.

Number of Items

The setBounds() method sets the minimum, maximum, and default number of items:

$persons->setBounds(min: 1, max: 10, default: 2);

The default number of empty items is created right away, so a fresh form is displayed to the user with two rows. The default parameter is optional and takes the value of min.

The number of submitted items is validated on the server just like any other rule. When the user does not respect the bounds (JavaScript can always be bypassed), the form will not be valid and an error message is displayed. The submitted data is never discarded – the user loses nothing and can correct the number of items. The message texts can be changed in the configuration under the identifiers forms.repeater.min and forms.repeater.max, or they are translated by the translator.

One more detail that you don't need to worry about, but is good to know: items are always renumbered on the server to a continuous sequence starting from zero. When the user deletes a middle row in the browser, no gaps appear in the data.

Rendering in Latte

In the template, we render the repeater with the paired {repeater} tag. Its content is repeated for each item, and tags like {input} or {label} inside it refer to the item's controls:

{form registrationForm}
	{repeater persons}
		<div class="person">
			{label name /} {input name}
			{label email /} {input email}
			<button n:repeater-remove>Remove</button>
		</div>
	{/repeater}
	<button n:repeater-add="persons">Add person</button>

	{input send}
{/form}

The n:repeater-remove attribute marks a button that deletes its item; it is used inside {repeater} and takes no argument. The n:repeater-add attribute adds an item, so it usually stands after {/repeater} and takes the name of the repeater as its argument.

Both buttons are a purely client-side matter – they have no name attribute, nothing is sent to the server, and JavaScript takes care of everything. In addition to the items themselves, the {repeater} tag also generates a <template> element with a recipe for an empty item, from which new rows are cloned directly in the browser, without a single request to the server.

Repeaters can be nested, for example a list of persons where each has a list of e-mails:

{repeater persons}
	{label name /} {input name}

	{repeater emails}
		{input address}
		<button n:repeater-remove>×</button>
	{/repeater}
	<button n:repeater-add="emails">Add e-mail</button>

	<button n:repeater-remove>Remove person</button>
{/repeater}

You can have a template with a repeater generated for you using Blueprint::latte(), it supports the {repeater} tags including the buttons.

Table Layout

The {repeater} tag also exists in the form of an n:attribute, which you will appreciate when a specific HTML element should be the wrapper of the repeater. And the element repeated with each item is marked with the n:repeater-item attribute. A table with items as rows then looks like this:

<table>
	<thead>
		<tr><th>Description</th><th>Quantity</th><th></th></tr>
	</thead>
	<tbody n:repeater=items>
		<tr n:repeater-item>
			<td>{input description}</td>
			<td>{input quantity}</td>
			<td><button n:repeater-remove>Remove</button></td>
		</tr>
	</tbody>
</table>
<button n:repeater-add="items">Add row</button>

The element with n:repeater becomes the wrapper of the repeater and the element with n:repeater-item is repeated for each item. Both tags and their attributes are fully in your hands.

If you omit n:repeater-item, the entire content of the element becomes the item recipe and Nette supplies the item wrapper: a <div> by default, which you can change via the getItemPrototype() prototype. The same rule applies to the paired {repeater} tag, where the getContainerPrototype() prototype also produces the wrapper of the whole repeater.

Prototypes also exist for the buttons: getAddButtonPrototype() and getRemoveButtonPrototype(). The configured attributes and text are used everywhere Nette renders the button, for example in a template generated by Blueprint:

$items->getAddButtonPrototype()
	->setText('Add row')
	->class('btn btn-secondary');

JavaScript

Adding and removing items is handled by the nette-forms script, the same one that takes care of JavaScript validation. Nothing else is needed – new items are cloned from the recipe in the <template> element, receive the correct names, ids, and validation rules, and immediately join the form validation.

Moreover, the add and remove buttons are automatically disabled (the disabled attribute) as soon as the number of items hits the bounds set via setBounds().

If you want to intervene in the process, listen to the events that the repeater dispatches on its wrapping element and which bubble up through the document:

event when it occurs detail
repeater:add before an item is added, cancelable container, item, index
repeater:added after an item is inserted into the page container, item, index
repeater:remove before an item is removed, cancelable container, item, modified

The repeater:add and repeater:remove events can be canceled using the preventDefault() method, which prevents the action. The modified flag tells whether the user has filled in anything in the item – this makes it easy to add a confirmation dialog before deleting a row with unsaved work:

document.addEventListener('repeater:remove', (e) => {
	if (e.detail.modified && !confirm('The item contains unsaved changes. Really remove it?')) {
		e.preventDefault();
	}
});

The repeater:added event, in turn, is useful for initializing JavaScript widgets (such as a datepicker) in a newly added item.

Mapping to Classes

Repeater supports mapping to classes. Since it returns an array of items, the class to which individual items should be mapped is passed using the setMappedType() method:

class PersonFormData
{
	public string $name;
	public string $email;
}

$persons->setMappedType(PersonFormData::class);

$data = $form->getValues(RegistrationFormData::class);
// $data->persons is an array of PersonFormData objects

In the form data class, mark the repeater property with the array type.

Rendering without Latte

You don't even need a template. The default renderer renders the repeater completely, including the <template> element and the add and remove buttons made from the getAddButtonPrototype() and getRemoveButtonPrototype() prototypes, so a simple echo $form gives you a working dynamic form. The repeater is wrapped in a <fieldset class="repeater"> element, which you can change in the renderer's $wrappers['repeater']['container'] setting.

version: 4.x