Symfony Forms reference
In a nutshell
When used in Symfony applications, the symfony/forms
package makes it easier to work with forms in web applications. More specifically it can:
- Convert submitted form data into PHP objects (usually Doctrine entities) and vice-versa.
- Validate submitted data using validator constraints that are usually defined on Doctrine entities.
- Generate the HTML mark up using information defined in the Form Type class (see below).
- Display error messages when submission is invalid.
- Generate a hidden _token field to protect against CSRF attacks.
The forms workflow
When working with forms in Symfony, you usually take the following approach:
- Build the form in a controller or in a dedicated form class.
- Render the form in a template.
- Process the form in a controller to validate the submitted data, transform it into PHP data, and do something with it (e.g., persist it to a database).
Build a Form Type
This will generate src/Form/CommentFormType.php
that looks like this:
A form type is a class that describes form fields bound to an entity. Symfony converts between the submitted data and the entity class properties. It uses metadata from the corresponding entity (e.g., Doctrine metadata) to guess the configuration for each field. For example, it’ll render a text
property as a textarea
.
Display a form
1. Create the form in a controller action and pass it to the template
2. Render form in twig
This should render something like:

Customise a form
You can customize the buildForm
method to add, remove, or modify fields:
Validate form submission
1. Add validation constraints
Since most forms will be bound to a Doctrine entity, you’ll typically add validation constraints to your entities. For example:
4. Check if form is valid in controller
Now, when the form is submitted with invalid data, the Twig form()
method will show any validation errors:

Debug forms using the Symfony Profiler
Click on the Form panel:

You can view the validator calls:

Or view the submitted data and any errors.

Sources
Thanks for your comment . Once it's approved, it will appear here.
Leave a comment