Forms
Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.
Read the updated version of this page for Symfony 7.2 (the current stable version).
Forms are one of the most misused Symfony components due to its vast scope and endless list of features. In this chapter we'll show you some of the best practices so you can leverage forms but get work done quickly.
Building Forms
Best Practice
Define your forms as PHP classes.
The Form component allows you to build forms right inside your controller code. This is perfectly fine if you don't need to reuse the form somewhere else. But for organization and reuse, we recommend that you define each form in its own PHP class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
namespace AppBundle\Form;
use AppBundle\Entity\Post;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('summary', TextareaType::class)
->add('content', TextareaType::class)
->add('authorEmail', EmailType::class)
->add('publishedAt', DateTimeType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Post::class,
]);
}
}
Best Practice
Put the form type classes in the AppBundle\Form
namespace, unless you
use other custom form classes like data transformers.
To use the class, use createForm()
and pass the fully qualified class name:
1 2 3 4 5 6 7 8 9 10 11
// ...
use AppBundle\Form\PostType;
// ...
public function newAction(Request $request)
{
$post = new Post();
$form = $this->createForm(PostType::class, $post);
// ...
}
Registering Forms as Services
You can also register your form type as a service. This is only needed if your form type requires some dependencies to be injected by the container, otherwise it is unnecessary overhead and therefore not recommended to do this for all form type classes.
Form Button Configuration
Form classes should try to be agnostic to where they will be used. This makes them easier to re-use later.
Best Practice
Add buttons in the templates, not in the form classes or the controllers.
The Symfony Form component allows you to add buttons as fields on your form. This is a nice way to simplify the template that renders your form. But if you add the buttons directly in your form class, this would effectively limit the scope of that form:
1 2 3 4 5 6 7 8 9 10 11 12
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('save', SubmitType::class, ['label' => 'Create Post'])
;
}
// ...
}
This form may have been designed for creating posts, but if you wanted to reuse it for editing posts, the button label would be wrong. Instead, some developers configure form buttons in the controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
namespace AppBundle\Controller\Admin;
use AppBundle\Entity\Post;
use AppBundle\Form\PostType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
class PostController extends Controller
{
// ...
public function newAction(Request $request)
{
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->add('submit', SubmitType::class, [
'label' => 'Create',
'attr' => ['class' => 'btn btn-default pull-right'],
]);
// ...
}
}
This is also an important error, because you are mixing presentation markup (labels, CSS classes, etc.) with pure PHP code. Separation of concerns is always a good practice to follow, so put all the view-related things in the view layer:
1 2 3 4 5 6
{{ form_start(form) }}
{{ form_widget(form) }}
<input type="submit" value="Create"
class="btn btn-default pull-right"/>
{{ form_end(form) }}
Validation
The constraints option allows you to attach validation constraints to any form field. However, doing that prevents the validation from being reused in other forms or other places where the mapped object is used.
Best Practice
Do not define your validation constraints in the form but on the object the form is mapped to.
For example, to validate that the title of the post edited with a form is not
blank, add the following in the Post
object:
1 2 3 4 5 6 7 8 9 10 11 12
// src/Entity/Post.php
// ...
use Symfony\Component\Validator\Constraints as Assert;
class Post
{
/**
* @Assert\NotBlank
*/
public $title;
}
Rendering the Form
There are a lot of ways to render your form, ranging from rendering the entire thing in one line to rendering each part of each field independently. The best way depends on how much customization you need.
One of the simplest ways - which is especially useful during development -
is to render the form tags and use the form_widget()
function to render
all of the fields:
1 2 3
{{ form_start(form, {'attr': {'class': 'my-form-class'} }) }}
{{ form_widget(form) }}
{{ form_end(form) }}
If you need more control over how your fields are rendered, then you should
remove the form_widget(form)
function and render your fields individually.
See How to Customize Form Rendering for more information on this and how you
can control how the form renders at a global level using form theming.
Handling Form Submits
Handling a form submit usually follows a similar template:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public function newAction(Request $request)
{
// build the form ...
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($post);
$entityManager->flush();
return $this->redirect($this->generateUrl(
'admin_post_show',
['id' => $post->getId()]
));
}
// render the template
}
There are really only two notable things here. First, we recommend that you
use a single action for both rendering the form and handling the form submit.
For example, you could have a newAction()
that only renders the form
and a createAction()
that only processes the form submit. Both those
actions will be almost identical. So it's much simpler to let newAction()
handle everything.
Second, is it required to call $form->isSubmitted()
in the if
statement
before calling isValid()
. Calling isValid()
with an unsubmitted form
is deprecated since version 3.2 and will throw an exception in 4.0.
Next: Internationalization