The Form Component

The Form Component

The Form component allows you to create, process and reuse forms.

The Form component is a tool to help you solve the problem of allowing end-users to interact with the data and modify the data in your application. And though traditionally this has been through HTML forms, the component focuses on processing data to and from your client and application, whether that data be from a normal form post or from an API.

Installation

  1. $ composer require symfony/form

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Configuration

See also

This article explains how to use the Form features as an independent component in any PHP application. Read the Forms article to learn about how to use it in Symfony applications.

In Symfony, forms are represented by objects and these objects are built by using a form factory. Building a form factory is done with the factory method Forms::createFormFactory:

  1. use Symfony\Component\Form\Forms;
  2. $formFactory = Forms::createFormFactory();

This factory can already be used to create basic forms, but it is lacking support for very important features:

  • Request Handling: Support for request handling and file uploads;
  • CSRF Protection: Support for protection against Cross-Site-Request-Forgery (CSRF) attacks;
  • Templating: Integration with a templating layer that allows you to reuse HTML fragments when rendering a form;
  • Translation: Support for translating error messages, field labels and other strings;
  • Validation: Integration with a validation library to generate error messages for submitted data.

The Symfony Form component relies on other libraries to solve these problems. Most of the time you will use Twig and the Symfony HttpFoundation, Translation and Validator components, but you can replace any of these with a different library of your choice.

The following sections explain how to plug these libraries into the form factory.

Tip

For a working example, see https://github.com/webmozart/standalone-forms

Request Handling

To process form data, you’ll need to call the handleRequest() method:

  1. $form->handleRequest();

Behind the scenes, this uses a Symfony\Component\Form\NativeRequestHandler object to read data off of the correct PHP superglobals (i.e. $_POST or $_GET) based on the HTTP method configured on the form (POST is default).

See also

If you need more control over exactly when your form is submitted or which data is passed to it, use the submit() method to handle form submissions.

Integration with the HttpFoundation Component

If you use the HttpFoundation component, then you should add the Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension to your form factory:

  1. use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
  2. use Symfony\Component\Form\Forms;
  3. $formFactory = Forms::createFormFactoryBuilder()
  4. ->addExtension(new HttpFoundationExtension())
  5. ->getFormFactory();

Now, when you process a form, you can pass the Symfony\Component\HttpFoundation\Request object to handleRequest():

  1. $form->handleRequest($request);

Note

For more information about the HttpFoundation component or how to install it, see The HttpFoundation Component.

CSRF Protection

Protection against CSRF attacks is built into the Form component, but you need to explicitly enable it or replace it with a custom solution. If you want to use the built-in support, first install the Security CSRF component:

  1. $ composer require symfony/security-csrf

The following snippet adds CSRF protection to the form factory:

  1. use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
  2. use Symfony\Component\Form\Forms;
  3. use Symfony\Component\HttpFoundation\RequestStack;
  4. use Symfony\Component\Security\Csrf\CsrfTokenManager;
  5. use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
  6. use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
  7. // creates a RequestStack object using the current request
  8. $requestStack = new RequestStack();
  9. $requestStack->push($request);
  10. $csrfGenerator = new UriSafeTokenGenerator();
  11. $csrfStorage = new SessionTokenStorage($requestStack);
  12. $csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
  13. $formFactory = Forms::createFormFactoryBuilder()
  14. // ...
  15. ->addExtension(new CsrfExtension($csrfManager))
  16. ->getFormFactory();

Internally, this extension will automatically add a hidden field to every form (called _token by default) whose value is automatically generated by the CSRF generator and validated when binding the form.

Tip

If you’re not using the HttpFoundation component, you can use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage instead, which relies on PHP’s native session handling:

  1. use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage;
  2. $csrfStorage = new NativeSessionTokenStorage();
  3. // ...

You can disable CSRF protection per form using the csrf_protection option:

  1. use Symfony\Component\Form\Extension\Core\Type\FormType;
  2. $form = $formFactory->createBuilder(FormType::class, null, ['csrf_protection' => false])
  3. ->getForm();

Twig Templating

If you’re using the Form component to process HTML forms, you’ll need a way to render your form as HTML form fields (complete with field values, errors, and labels). If you use Twig as your template engine, the Form component offers a rich integration.

To use the integration, you’ll need the twig bridge, which provides integration between Twig and several Symfony components:

  1. $ composer require symfony/twig-bridge

The TwigBridge integration provides you with several Twig Functions that help you render the HTML widget, label, help and errors for each field (as well as a few other things). To configure the integration, you’ll need to bootstrap or access Twig and add the Symfony\Bridge\Twig\Extension\FormExtension:

  1. use Symfony\Bridge\Twig\Extension\FormExtension;
  2. use Symfony\Bridge\Twig\Form\TwigRendererEngine;
  3. use Symfony\Component\Form\FormRenderer;
  4. use Symfony\Component\Form\Forms;
  5. use Twig\Environment;
  6. use Twig\Loader\FilesystemLoader;
  7. use Twig\RuntimeLoader\FactoryRuntimeLoader;
  8. // the Twig file that holds all the default markup for rendering forms
  9. // this file comes with TwigBridge
  10. $defaultFormTheme = 'form_div_layout.html.twig';
  11. $vendorDirectory = realpath(__DIR__.'/../vendor');
  12. // the path to TwigBridge library so Twig can locate the
  13. // form_div_layout.html.twig file
  14. $appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
  15. $vendorTwigBridgeDirectory = dirname($appVariableReflection->getFileName());
  16. // the path to your other templates
  17. $viewsDirectory = realpath(__DIR__.'/../views');
  18. $twig = new Environment(new FilesystemLoader([
  19. $viewsDirectory,
  20. $vendorTwigBridgeDirectory.'/Resources/views/Form',
  21. ]));
  22. $formEngine = new TwigRendererEngine([$defaultFormTheme], $twig);
  23. $twig->addRuntimeLoader(new FactoryRuntimeLoader([
  24. FormRenderer::class => function () use ($formEngine, $csrfManager) {
  25. return new FormRenderer($formEngine, $csrfManager);
  26. },
  27. ]));
  28. // ... (see the previous CSRF Protection section for more information)
  29. // adds the FormExtension to Twig
  30. $twig->addExtension(new FormExtension());
  31. // creates a form factory
  32. $formFactory = Forms::createFormFactoryBuilder()
  33. // ...
  34. ->getFormFactory();

New in version 1.30: The Twig\RuntimeLoader\FactoryRuntimeLoader was introduced in Twig 1.30.

The exact details of your Twig Configuration will vary, but the goal is always to add the Symfony\Bridge\Twig\Extension\FormExtension to Twig, which gives you access to the Twig functions for rendering forms. To do this, you first need to create a Symfony\Bridge\Twig\Form\TwigRendererEngine, where you define your form themes (i.e. resources/files that define form HTML markup).

For general details on rendering forms, see How to Customize Form Rendering.

Note

If you use the Twig integration, read “Translation” below for details on the needed translation filters.

Translation

If you’re using the Twig integration with one of the default form theme files (e.g. form_div_layout.html.twig), there is a Twig filter (trans) that is used for translating form labels, errors, option text and other strings.

To add the trans Twig filter, you can either use the built-in Symfony\Bridge\Twig\Extension\TranslationExtension that integrates with Symfony’s Translation component, or add the Twig filter yourself, via your own Twig extension.

To use the built-in integration, be sure that your project has Symfony’s Translation and Config components installed:

  1. $ composer require symfony/translation symfony/config

Next, add the Symfony\Bridge\Twig\Extension\TranslationExtension to your Twig\Environment instance:

  1. use Symfony\Bridge\Twig\Extension\TranslationExtension;
  2. use Symfony\Component\Form\Forms;
  3. use Symfony\Component\Translation\Loader\XliffFileLoader;
  4. use Symfony\Component\Translation\Translator;
  5. // creates the Translator
  6. $translator = new Translator('en');
  7. // somehow load some translations into it
  8. $translator->addLoader('xlf', new XliffFileLoader());
  9. $translator->addResource(
  10. 'xlf',
  11. __DIR__.'/path/to/translations/messages.en.xlf',
  12. 'en'
  13. );
  14. // adds the TranslationExtension (it gives us trans filter)
  15. $twig->addExtension(new TranslationExtension($translator));
  16. $formFactory = Forms::createFormFactoryBuilder()
  17. // ...
  18. ->getFormFactory();

Depending on how your translations are being loaded, you can now add string keys, such as field labels, and their translations to your translation files.

For more details on translations, see Translations.

Validation

The Form component comes with tight (but optional) integration with Symfony’s Validator component. If you’re using a different solution for validation, no problem! Take the submitted/bound data of your form (which is an array or object) and pass it through your own validation system.

To use the integration with Symfony’s Validator component, first make sure it’s installed in your application:

  1. $ composer require symfony/validator

If you’re not familiar with Symfony’s Validator component, read more about it: Validation. The Form component comes with a Symfony\Component\Form\Extension\Validator\ValidatorExtension class, which automatically applies validation to your data on bind. These errors are then mapped to the correct field and rendered.

Your integration with the Validation component will look something like this:

  1. use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
  2. use Symfony\Component\Form\Forms;
  3. use Symfony\Component\Validator\Validation;
  4. $vendorDirectory = realpath(__DIR__.'/../vendor');
  5. $vendorFormDirectory = $vendorDirectory.'/symfony/form';
  6. $vendorValidatorDirectory = $vendorDirectory.'/symfony/validator';
  7. // creates the validator - details will vary
  8. $validator = Validation::createValidator();
  9. // there are built-in translations for the core error messages
  10. $translator->addResource(
  11. 'xlf',
  12. $vendorFormDirectory.'/Resources/translations/validators.en.xlf',
  13. 'en',
  14. 'validators'
  15. );
  16. $translator->addResource(
  17. 'xlf',
  18. $vendorValidatorDirectory.'/Resources/translations/validators.en.xlf',
  19. 'en',
  20. 'validators'
  21. );
  22. $formFactory = Forms::createFormFactoryBuilder()
  23. // ...
  24. ->addExtension(new ValidatorExtension($validator))
  25. ->getFormFactory();

To learn more, skip down to the Form Validation section.

Accessing the Form Factory

Your application only needs one form factory, and that one factory object should be used to create any and all form objects in your application. This means that you should create it in some central, bootstrap part of your application and then access it whenever you need to build a form.

Note

In this document, the form factory is always a local variable called $formFactory. The point here is that you will probably need to create this object in some more “global” way so you can access it from anywhere.

Exactly how you gain access to your one form factory is up to you. If you’re using a service container (like provided with the DependencyInjection component), then you should add the form factory to your container and grab it out whenever you need to. If your application uses global or static variables (not usually a good idea), then you can store the object on some static class or do something similar.

Regardless of how you architect your application, remember that you should only have one form factory and that you’ll need to be able to access it throughout your application.

Creating a simple Form

Tip

If you’re using the Symfony Framework, then the form factory is available automatically as a service called form.factory. Also, the default base controller class has a createFormBuilder() method, which is a shortcut to fetch the form factory and call `createBuilder() on it.

Creating a form is done via a Symfony\Component\Form\FormBuilder object, where you build and configure different fields. The form builder is created from the form factory.

  • Standalone Use

    1. use Symfony\Component\Form\Extension\Core\Type\TextType;
    2. use Symfony\Component\Form\Extension\Core\Type\DateType;
    3. // ...
    4. $form = $formFactory->createBuilder()
    5. ->add('task', TextType::class)
    6. ->add('dueDate', DateType::class)
    7. ->getForm();
    8. var_dump($twig->render('new.html.twig', [
    9. 'form' => $form->createView(),
    10. ]));
  • Framework Use

    1. // src/Controller/TaskController.php
    2. namespace App\Controller;
    3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    4. use Symfony\Component\HttpFoundation\Request;
    5. use Symfony\Component\Form\Extension\Core\Type\TextType;
    6. use Symfony\Component\Form\Extension\Core\Type\DateType;
    7. class TaskController extends AbstractController
    8. {
    9. public function new(Request $request)
    10. {
    11. // createFormBuilder is a shortcut to get the "form factory"
    12. // and then call "createBuilder()" on it
    13. $form = $this->createFormBuilder()
    14. ->add('task', TextType::class)
    15. ->add('dueDate', DateType::class)
    16. ->getForm();
    17. return $this->render('task/new.html.twig', [
    18. 'form' => $form->createView(),
    19. ]);
    20. }
    21. }

As you can see, creating a form is like writing a recipe: you call add() for each new field you want to create. The first argument toadd() is the name of your field, and the second is the fully qualified class name. The Form component comes with a lot of built-in types.

Now that you’ve built your form, learn how to render it and process the form submission.

Setting default Values

If you need your form to load with some default values (or you’re building an “edit” form), pass in the default data when creating your form builder:

  • Standalone Use

    1. use Symfony\Component\Form\Extension\Core\Type\FormType;
    2. use Symfony\Component\Form\Extension\Core\Type\TextType;
    3. use Symfony\Component\Form\Extension\Core\Type\DateType;
    4. // ...
    5. $defaults = [
    6. 'dueDate' => new \DateTime('tomorrow'),
    7. ];
    8. $form = $formFactory->createBuilder(FormType::class, $defaults)
    9. ->add('task', TextType::class)
    10. ->add('dueDate', DateType::class)
    11. ->getForm();
  • Framework Use

    1. // src/Controller/DefaultController.php
    2. namespace App\Controller;
    3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    4. use Symfony\Component\Form\Extension\Core\Type\TextType;
    5. use Symfony\Component\Form\Extension\Core\Type\DateType;
    6. class DefaultController extends AbstractController
    7. {
    8. public function new(Request $request)
    9. {
    10. $defaults = [
    11. 'dueDate' => new \DateTime('tomorrow'),
    12. ];
    13. $form = $this->createFormBuilder($defaults)
    14. ->add('task', TextType::class)
    15. ->add('dueDate', DateType::class)
    16. ->getForm();
    17. // ...
    18. }
    19. }

Tip

In this example, the default data is an array. Later, when you use the data_class option to bind data directly to objects, your default data will be an instance of that object.

Rendering the Form

Now that the form has been created, the next step is to render it. This is done by passing a special form “view” object to your template (notice the `$form->createView() in the controller above) and using a set of form helper functions:

  1. {{ form_start(form) }}
  2. {{ form_widget(form) }}
  3. <input type="submit"/>
  4. {{ form_end(form) }}

../_images/simple-form.png

That’s it! By printing `form_widget(form), each field in the form is rendered, along with a label and error message (if there is one). While this is convenient, it’s not very flexible (yet). Usually, you’ll want to render each form field individually so you can control how the form looks. You’ll learn how to do that in the form customization article.

Changing a Form’s Method and Action

By default, a form is submitted to the same URI that rendered the form with an HTTP POST request. This behavior can be changed using the action and method options (the method option is also used by handleRequest() to determine whether a form has been submitted):

  • Standalone Use

    1. use Symfony\Component\Form\Extension\Core\Type\FormType;
    2. // ...
    3. $formBuilder = $formFactory->createBuilder(FormType::class, null, [
    4. 'action' => '/search',
    5. 'method' => 'GET',
    6. ]);
    7. // ...
  • Framework Use

    1. // src/Controller/DefaultController.php
    2. namespace App\Controller;
    3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    4. use Symfony\Component\Form\Extension\Core\Type\FormType;
    5. class DefaultController extends AbstractController
    6. {
    7. public function search()
    8. {
    9. $formBuilder = $this->createFormBuilder(null, [
    10. 'action' => '/search',
    11. 'method' => 'GET',
    12. ]);
    13. // ...
    14. }
    15. }

Handling Form Submissions

To handle form submissions, use the handleRequest() method:

  • Standalone Use

    1. use Symfony\Component\HttpFoundation\Request;
    2. use Symfony\Component\HttpFoundation\RedirectResponse;
    3. use Symfony\Component\Form\Extension\Core\Type\DateType;
    4. use Symfony\Component\Form\Extension\Core\Type\TextType;
    5. // ...
    6. $form = $formFactory->createBuilder()
    7. ->add('task', TextType::class)
    8. ->add('dueDate', DateType::class)
    9. ->getForm();
    10. $request = Request::createFromGlobals();
    11. $form->handleRequest($request);
    12. if ($form->isSubmitted() && $form->isValid()) {
    13. $data = $form->getData();
    14. // ... perform some action, such as saving the data to the database
    15. $response = new RedirectResponse('/task/success');
    16. $response->prepare($request);
    17. return $response->send();
    18. }
    19. // ...
  • Framework Use

    1. // src/Controller/TaskController.php
    2. namespace App\Controller;
    3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    4. use Symfony\Component\Form\Extension\Core\Type\DateType;
    5. use Symfony\Component\Form\Extension\Core\Type\TextType;
    6. class TaskController extends AbstractController
    7. {
    8. public function new(Request $request)
    9. {
    10. $form = $this->createFormBuilder()
    11. ->add('task', TextType::class)
    12. ->add('dueDate', DateType::class)
    13. ->getForm();
    14. $form->handleRequest($request);
    15. if ($form->isSubmitted() && $form->isValid()) {
    16. $data = $form->getData();
    17. // ... perform some action, such as saving the data to the database
    18. return $this->redirectToRoute('task_success');
    19. }
    20. // ...
    21. }
    22. }

This defines a common form “workflow”, which contains 3 different possibilities:

  1. On the initial GET request (i.e. when the user “surfs” to your page), build your form and render it;

If the request is a POST, process the submitted data (via handleRequest()). Then:

  1. if the form is invalid, re-render the form (which will now contain errors);
  2. if the form is valid, perform some action and redirect.

Luckily, you don’t need to decide whether or not a form has been submitted. Just pass the current request to the handleRequest() method. Then, the Form component will do all the necessary work for you.

Form Validation

The easiest way to add validation to your form is via the constraints option when building each field:

  • Standalone Use

    1. use Symfony\Component\Validator\Constraints\NotBlank;
    2. use Symfony\Component\Validator\Constraints\Type;
    3. use Symfony\Component\Form\Extension\Core\Type\TextType;
    4. use Symfony\Component\Form\Extension\Core\Type\DateType;
    5. $form = $formFactory->createBuilder()
    6. ->add('task', TextType::class, [
    7. 'constraints' => new NotBlank(),
    8. ])
    9. ->add('dueDate', DateType::class, [
    10. 'constraints' => [
    11. new NotBlank(),
    12. new Type(\DateTime::class),
    13. ]
    14. ])
    15. ->getForm();
  • Framework Use

    1. // src/Controller/DefaultController.php
    2. namespace App\Controller;
    3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    4. use Symfony\Component\Validator\Constraints\NotBlank;
    5. use Symfony\Component\Validator\Constraints\Type;
    6. use Symfony\Component\Form\Extension\Core\Type\DateType;
    7. use Symfony\Component\Form\Extension\Core\Type\TextType;
    8. class DefaultController extends AbstractController
    9. {
    10. public function new(Request $request)
    11. {
    12. $form = $this->createFormBuilder()
    13. ->add('task', TextType::class, [
    14. 'constraints' => new NotBlank(),
    15. ])
    16. ->add('dueDate', DateType::class, [
    17. 'constraints' => [
    18. new NotBlank(),
    19. new Type(\DateTime::class),
    20. ]
    21. ])
    22. ->getForm();
    23. // ...
    24. }
    25. }

When the form is bound, these validation constraints will be applied automatically and the errors will display next to the fields on error.

Note

For a list of all of the built-in validation constraints, see Validation Constraints Reference.

Accessing Form Errors

You can use the getErrors() method to access the list of errors. It returns a Symfony\Component\Form\FormErrorIterator instance:

  1. $form = ...;
  2. // ...
  3. // a FormErrorIterator instance, but only errors attached to this
  4. // form level (e.g. global errors)
  5. $errors = $form->getErrors();
  6. // a FormErrorIterator instance, but only errors attached to the
  7. // "firstName" field
  8. $errors = $form['firstName']->getErrors();
  9. // a FormErrorIterator instance in a flattened structure
  10. // use getOrigin() to determine the form causing the error
  11. $errors = $form->getErrors(true);
  12. // a FormErrorIterator instance representing the form tree structure
  13. $errors = $form->getErrors(true, false);

Clearing Form Errors

Any errors can be manually cleared using the clearErrors() method. This is useful when you’d like to validate the form without showing validation errors to the user (i.e. during a partial AJAX submission or dynamic form modification).

Because clearing the errors makes the form valid, clearErrors() should only be called after testing whether the form is valid.

Learn more

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