Forms¶
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 App\Form;
use App\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 App\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 App\Form\PostType;
// ...
public function new(Request $request)
{
$post = new Post();
$form = $this->createForm(PostType::class, $post);
// ...
}
|