Skip to content

RepeatedType Field

Edit this page

This is a special field "group", that creates two identical fields whose values must match (or a validation error is thrown). The most common use is when you need the user to repeat their password or email to verify accuracy.

Rendered as input text field by default, but see type option
Default invalid message The values do not match.
Legacy invalid message The value {{ value }} is not valid.
Parent type FormType
Class RepeatedType

Tip

The full list of options defined and inherited by this form type is available running this command in your app:

1
2
# replace 'FooType' by the class name of your form type
$ php bin/console debug:form FooType

Example Usage

1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
// ...

$builder->add('password', RepeatedType::class, [
    'type' => PasswordType::class,
    'invalid_message' => 'The password fields must match.',
    'options' => ['attr' => ['class' => 'password-field']],
    'required' => true,
    'first_options'  => ['label' => 'Password'],
    'second_options' => ['label' => 'Repeat Password'],
]);

Upon a successful form submit, the value entered into both of the "password" fields becomes the data of the password key. In other words, even though two fields are actually rendered, the end data from the form is just the single value (usually a string) that you need.

The most important option is type, which can be any field type and determines the actual type of the two underlying fields. The options option is passed to each of those individual fields, meaning - in this example - any option supported by the PasswordType can be passed in this array.

Rendering

The repeated field type is actually two underlying fields, which you can render all at once, or individually. To render all at once, use something like:

1
{{ form_row(form.password) }}

To render each field individually, use something like this:

1
2
3
{# .first and .second may vary in your use - see the note below #}
{{ form_row(form.password.first) }}
{{ form_row(form.password.second) }}

Note

The names first and second are the default names for the two sub-fields. However, these names can be controlled via the first_name and second_name options. If you've set these options, then use those values instead of first and second when rendering.

Validation

One of the key features of the repeated field is internal validation (you don't need to do anything to set this up) that forces the two fields to have a matching value. If the two fields don't match, an error will be shown to the user.

The invalid_message is used to customize the error that will be displayed when the two fields do not match each other.

Note

The mapped option is always true for both fields in order for the type to work properly.

Field Options

first_name

type: string default: first

This is the actual field name to be used for the first field. This is mostly meaningless, however, as the actual data entered into both of the fields will be available under the key assigned to the RepeatedType field itself (e.g. password). However, if you don't specify a label, this field name is used to "guess" the label for you.

first_options

type: array default: []

Additional options (will be merged into options below) that should be passed only to the first field. This is especially useful for customizing the label:

1
2
3
4
5
6
7
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
// ...

$builder->add('password', RepeatedType::class, [
    'first_options'  => ['label' => 'Password'],
    'second_options' => ['label' => 'Repeat Password'],
]);

options

type: array default: []

This options array will be passed to each of the two underlying fields. In other words, these are the options that customize the individual field types. For example, if the type option is set to password, this array might contain the options always_empty or required - both options that are supported by the PasswordType field.

second_name

type: string default: second

The same as first_name, but for the second field.

second_options

type: array default: []

Additional options (will be merged into options above) that should be passed only to the second field. This is especially useful for customizing the label (see first_options).

type

type: string default: Symfony\Component\Form\Extension\Core\Type\TextType

The two underlying fields will be of this field type. For example, passing PasswordType::class will render two password fields.

Overridden Options

error_bubbling

default: false

invalid_message

type: string default: This value is not valid

This is the validation error message that's used if the data entered into this field doesn't make sense (i.e. fails validation).

This might happen, for example, if the user enters a nonsense string into a TimeType field that cannot be converted into a real time or if the user enters a string (e.g. apple) into a number field.

Normal (business logic) validation (such as when setting a minimum length for a field) should be set using validation messages with your validation rules (reference).

Inherited Options

These options inherit from the FormType:

attr

type: array default: []

If you want to add extra attributes to an HTML field representation you can use the attr option. It's an associative array with HTML attributes as keys. This can be useful when you need to set a custom class for some widget:

1
2
3
$builder->add('body', TextareaType::class, [
    'attr' => ['class' => 'tinymce'],
]);

See also

Use the row_attr option if you want to add these attributes to the form type row element.

data

type: mixed default: Defaults to field of the underlying structure.

When you create a form, each field initially displays the value of the corresponding property of the form's domain data (e.g. if you bind an object to the form). If you want to override this initial value for the form or an individual field, you can set it in the data option:

1
2
3
4
5
6
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
// ...

$builder->add('token', HiddenType::class, [
    'data' => 'abcdef',
]);

Caution

The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overridden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted.

error_mapping

type: array default: []

This option allows you to modify the target of a validation error.

Imagine you have a custom method named matchingCityAndZipCode() that validates whether the city and zip code match. Unfortunately, there is no matchingCityAndZipCode field in your form, so all that Symfony can do is display the error on top of the form.

With customized error mapping, you can do better: map the error to the city field so that it displays above it:

1
2
3
4
5
6
7
8
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'error_mapping' => [
            'matchingCityAndZipCode' => 'city',
        ],
    ]);
}

Here are the rules for the left and the right side of the mapping:

  • The left side contains property paths;
  • If the violation is generated on a property or method of a class, its path is the propertyName;
  • If the violation is generated on an entry of an array or ArrayAccess object, the property path is [indexName];
  • You can construct nested property paths by concatenating them, separating properties by dots. For example: addresses[work].matchingCityAndZipCode;
  • The right side contains the names of fields in the form.

By default, errors for any property that is not mapped will bubble up to the parent form. You can use the dot (.) on the left side to map errors of all unmapped properties to a particular field. For instance, to map all these errors to the city field, use:

1
2
3
4
5
$resolver->setDefaults([
    'error_mapping' => [
        '.' => 'city',
    ],
]);

help

type: string or TranslatableMessage default: null

Allows you to define a help message for the form field, which by default is rendered below the field:

1
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\Translation\TranslatableMessage;

$builder
    ->add('zipCode', null, [
        'help' => 'The ZIP/Postal code for your credit card\'s billing address.',
    ])

    // ...

    ->add('status', null, [
        'help' => new TranslatableMessage('order.status', ['%order_id%' => $order->getId()], 'store'),
    ])
;

5.4

Support for passing TranslatableMessage objects was introduced in Symfony 5.4.

help_attr

type: array default: []

Sets the HTML attributes for the element used to display the help message of the form field. Its value is an associative array with HTML attribute names as keys. These attributes can also be set in the template:

1
2
3
{{ form_help(form.name, 'Your name', {
    'help_attr': {'class': 'CUSTOM_LABEL_CLASS'}
}) }}

help_html

type: boolean default: false

By default, the contents of the help option are escaped before rendering them in the template. Set this option to true to not escape them, which is useful when the help contains HTML elements.

invalid_message_parameters

type: array default: []

When setting the invalid_message option, you may need to include some variables in the string. This can be done by adding placeholders to that option and including the variables in this option:

1
2
3
4
5
$builder->add('someField', SomeFormType::class, [
    // ...
    'invalid_message' => 'You entered an invalid value, it should include %num% letters',
    'invalid_message_parameters' => ['%num%' => 6],
]);

mapped

type: boolean default: true

If you wish the field to be ignored when reading or writing to the object, you can set the mapped option to false.

row_attr

type: array default: []

An associative array of the HTML attributes added to the element which is used to render the form type row:

1
2
3
$builder->add('body', TextareaType::class, [
    'row_attr' => ['class' => 'text-editor', 'id' => '...'],
]);

See also

Use the attr option if you want to add these attributes to the form type widget element.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version