Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 62 ยท Forms and Validation

Form Types and Options

Tour the most useful Symfony form types (text, choice, entity, date, collection, file) and the options every field shares, plus data classes and empty_data.

In Forms: Building and Rendering you built a form from three field types. Symfony ships with about fifty. Each form type knows three things: which HTML to render, how to convert the submitted string into the right PHP value (an integer, a date, an enum, a list), and how to turn that PHP value back into text when the form is displayed.

Choosing the right type is what saves you from writing conversion code by hand, and the options you pass tune the behavior. This lesson walks through the types you will use most, the options almost every type shares, and how forms map onto data classes. The real Symfony code is read-only. The runnable examples are plain-PHP stand-ins for the conversion step and for the OptionsResolver that validates options.

Text-like types

These render a single <input> (or <textarea>) and give back a string:

Type HTML Notes
TextType <input type="text"> The default workhorse
TextareaType <textarea> Multi-line text
EmailType <input type="email"> Browser hint only: does not validate
PasswordType <input type="password"> Never re-displays the value (always_empty)
UrlType, SearchType, TelType, ColorType the matching type attribute Browser hints
HiddenType <input type="hidden"> Never trust it: users can edit hidden fields

Numbers have their own types because they convert the submitted text:

  • IntegerType returns an int and reports an error for text that is not a whole number.
  • NumberType returns a float and accepts decimals (use scale to round).
  • MoneyType formats an amount with a currency symbol ('currency' => 'EUR'). Set divisor (for example 100) if your model keeps the amount in cents.
  • PercentType and RangeType cover percentages and sliders.

Two conversions often surprise people. A text field submitted empty gives null, not an empty string, so a setter such as setTitle(string $title) receives null and raises a TypeError unless the property is nullable or you set empty_data. And trim is on by default: surrounding spaces are removed from submitted text.

Choosing from a list

ChoiceType is the most flexible type. It renders a <select>, a set of radio buttons or checkboxes, depending on two options:

expanded multiple Renders
false false A <select> (one value)
false true A multi <select>
true false Radio buttons
true true Checkboxes
PHP
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

$builder->add('priority', ChoiceType::class, [
    'choices' => [
        'Low' => 1,       // label => value
        'Normal' => 2,
        'Urgent' => 3,
    ],
    'placeholder' => 'Choose a priority',
    'expanded' => false,
]);

The array maps the label (what the user sees) to the value (what you get in PHP). A submitted value that is not among the choices is rejected as invalid, which is a useful security property: a user cannot post priority=99. Add 'choice_label' => ... and 'choice_value' => ... callbacks when the choices are objects, and group_by to build <optgroup>s.

When the choices are a PHP backed enum, use EnumType:

PHP
use Symfony\Component\Form\Extension\Core\Type\EnumType;

$builder->add('status', EnumType::class, [
    'class' => TaskStatus::class,
    'choice_label' => fn (TaskStatus $status): string => ucfirst($status->value),
]);

For database rows there is EntityType, provided by the Doctrine bridge (installed with Doctrine). It turns entities into choices:

PHP
use App\Entity\Category;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

$builder->add('category', EntityType::class, [
    'class' => Category::class,
    'choice_label' => 'name',
    'query_builder' => fn (CategoryRepository $repository) => $repository
        ->createQueryBuilder('c')
        ->orderBy('c.name', 'ASC'),
    'placeholder' => 'Pick a category',
]);

Symfony loads the categories, renders their ids as option values, and converts the submitted id back into the entity. Set multiple for a to-many relation. For long lists (thousands of rows) a plain select is a poor user interface and a heavy query; use an autocomplete component instead.

CheckboxType is a single yes/no box and gives a bool. It needs 'required' => false unless the user must tick it.

Dates and times

DateType, TimeType and DateTimeType convert text to PHP date objects. Two options matter most:

  • widget: choice (several selects, the default), text or single_text. single_text renders one HTML5 date input, which is what most sites want.
  • input: the PHP type you get: datetime (default), datetime_immutable, string, timestamp or array. Use datetime_immutable for modern code.
PHP
$builder->add('dueDate', DateType::class, [
    'widget' => 'single_text',
    'input' => 'datetime_immutable',
    'required' => false,
]);

BirthdayType, DateIntervalType and TimezoneType are specializations. Time zones deserve care: model_timezone and view_timezone options convert between the zone you store (use UTC) and the zone the user sees.

Collections and compound types

CollectionType renders a list of sub-forms, one per item, for example a task with several checklist items. You choose the sub-form with entry_type, and allow_add / allow_delete let users grow and shrink the list with a bit of JavaScript. It has enough details of its own to deserve a lesson: see Advanced Forms.

RepeatedType renders the same field twice and requires both values to match, which is the standard "type your password twice" pattern:

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

Many forms also embed another form type as a field (a task with an AddressType); that is covered in Advanced Forms as well.

File uploads

FileType renders <input type="file"> and gives an UploadedFile. Because an uploaded file is not a string you can map to a property, the field is usually unmapped and handled in the controller, with the File constraint doing the checks:

PHP
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;

$builder->add('attachment', FileType::class, [
    'mapped' => false,
    'required' => false,
    'constraints' => [new File(maxSize: '2M', mimeTypes: ['application/pdf'])],
]);

Moving and storing the file safely is the topic of File Uploads.

Options every type shares

Beyond the options of a specific type, all types accept a common set. These are the ones you will use daily:

Option Purpose
label The label text, or false to hide it
required Adds the HTML required attribute and a * style hook. It does not validate anything on the server
mapped false keeps the field out of the data object (read it with $form->get('x')->getData())
data A fixed initial value, overriding the object's property
empty_data The value used when the field is submitted empty
attr HTML attributes on the widget (['class' => 'wide', 'maxlength' => 80])
row_attr HTML attributes on the wrapping row
help A help text printed under the field
disabled Renders the field disabled and ignores submitted values
constraints Validation constraints for this field (see Validation)
property_path The property to read and write when the field name differs from it
trim Whether to trim submitted text (default true)

required is an HTML hint. A user can remove the attribute, or send a request without your form at all. Real validation belongs in validation constraints, which run on the server.

Data classes and options of the form itself

A form type has options too. You set defaults in configureOptions() and callers can pass overrides as the third argument of createForm():

PHP
public function configureOptions(OptionsResolver $resolver): void
{
    $resolver->setDefaults([
        'data_class' => Task::class,
        'is_edit' => false,           // our own option
    ]);
    $resolver->setAllowedTypes('is_edit', 'bool');
}

public function buildForm(FormBuilderInterface $builder, array $options): void
{
    $builder->add('title', TextType::class);
    if ($options['is_edit']) {
        $builder->add('done', CheckboxType::class, ['required' => false]);
    }
}
PHP
$form = $this->createForm(TaskType::class, $task, ['is_edit' => true]);

The OptionsResolver is a standalone component that Symfony uses everywhere (forms, HTTP client, mailer). It rejects unknown options and wrong types early, with a readable message, which turns typos like 'requierd' => false into immediate errors.

The data class can be an entity, a plain object or a small DTO class dedicated to the form. For immutable objects, whose constructor needs values, use empty_data as a closure that builds the object from the submitted fields:

PHP
$resolver->setDefaults([
    'data_class' => TaskDto::class,
    'empty_data' => fn (FormInterface $form) => new TaskDto(
        title: $form->get('title')->getData() ?? '',
        priority: $form->get('priority')->getData() ?? 2,
    ),
]);

Using a separate DTO for a form keeps validation rules about user input apart from your entity's persistence rules, which pays off as forms grow.

A runnable stand-in for the conversion

Each type is, at its core, a pair of conversions with a failure message. The stand-in below implements that idea for a few types, using messages that resemble Symfony's defaults. It is not the real component, but it shows why IntegerType and ChoiceType give safer data than reading $_POST directly.

PHP What a form type does to submitted text (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Compare the three submissions. The valid post gives typed PHP values (note the trimmed title and the real int). The empty post gives null for every text-like field, which is why nullable properties and empty_data matter. The tampered post cannot sneak past ChoiceType, IntegerType or DateType. In real Symfony these failures become form errors on the field and the form is simply not valid.

The next stand-in is a small OptionsResolver. The real class has many more features (normalizers, lazy defaults, nested options), but required options, defaults, allowed types and allowed values are the part you will meet first.

PHP A mini OptionsResolver (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A mistyped option name stops the program immediately instead of being ignored. That early, loud failure is a big part of why configuring Symfony components is pleasant once you are used to it.

Choosing a type: a quick guide

flowchart TD
    A["What does the user provide?"] --> B{"Free text?"}
    B -->|"short"| C["TextType, EmailType, UrlType"]
    B -->|"long"| D["TextareaType"]
    A --> E{"One of a list?"}
    E -->|"fixed list or enum"| F["ChoiceType or EnumType"]
    E -->|"database rows"| G["EntityType"]
    A --> H{"Number or date?"}
    H --> I["IntegerType, NumberType, MoneyType<br/>DateType with single_text"]
    A --> J{"Repeated or a file?"}
    J --> K["CollectionType, RepeatedType, FileType"]

Pick the most specific type: it gives you the right HTML, the right PHP value and the right validation hint for free.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A TextType field is submitted empty. What does the form give you for it?

    Empty text becomes null. A non-nullable string setter needs a nullable property or an empty_data option.
  2. 2. What does 'required' => true (the default) do on the server?

    required is a browser hint. Use validation constraints such as NotBlank to enforce rules on the server.
  3. 3. Which ChoiceType options render a group of radio buttons?

    expanded true shows all options at once; multiple false limits the user to one, so radio buttons are used. Both true gives checkboxes.
  4. 4. Why is a file field usually declared with 'mapped' => false?

    The submitted UploadedFile is normally moved to storage, and only its new name is stored on the entity, so the field is handled separately.
  5. 5. What does the OptionsResolver do when you pass an option name that was never defined?

    Unknown options are rejected early with a clear message, which catches typos before they cause hard-to-find bugs.

Summary

  • A form type renders HTML and converts between submitted strings and PHP values; pick the most specific type available.
  • ChoiceType (with expanded and multiple), EnumType and EntityType handle lists, and invalid choices are rejected automatically.
  • Use widget: single_text and input: datetime_immutable for dates; empty text fields give null, so plan for nullable properties or empty_data.
  • Shared options such as label, mapped, attr, help, constraints and empty_data work on every type, but required is only an HTML hint.
  • Forms take options of their own through configureOptions() and the OptionsResolver; a data class can be an entity or a dedicated DTO.

Next up: Handling Submission and CSRF.