Symfony4/5 forms Cheatsheet

FormType / Configuration

  • // /src/Form/Type/FooFormType.php
    
    namespace App\Form\Type;
    
    class fooFormType extends AbstractType
    {
        // Inject a service
        protected $myService;
        public function __construct(MyService $myService)
        {
            $this->myService = $myService;
        }
    
        // Configure options
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'action' => '/my/url/',
                'csrf_protection' => false,
                'method' => 'GET',
    
                // bind to a data class (form binding returns this object as result)
                'data_class' => Foo::class,
    
                // pass custom options to the form
                'myOption => '',
            ]);
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            // Set a dynamic action
            $builder->setAction('/foo/ . $options['myOption'];
    
            $builder->add('first_name', TextType::class, [
                'required' => false,
                'label' => 'First name',
                'attr' => ['placeholder' => 'Enter your first name'],
            ]);
    
            $builder->add('secret', HiddenType::class, [
                'empty_data' => 'default',
                'required' => false,
                'label' => 'Secret',
            ]);
            // Set value for hidden
            $builder->setData(['bereich' => $options['bereich']]);
    
    
            // Use service
            $this->myService->doSomething();
    
            // Use options
            $options['myOption'];
        }
    }

 

Set Placeholder for TextType Field

Why not support 'placeholder' option like in ChoiceType?
https://github.com/symfony/symfony/issues/45214

  • $builder->add('location', TextType::class, [
        'attr' => ['placeholder' => 'Town or State)'],
    ]);

Form Builder

With a lot of options

  •     $formBuilder = $formFactory->createNamedBuilder(
            'filterForm',
            FormType::class,
            null,
            ['csrf_protection' => false,
            'attr' => ['id' => 'filter-form']
        ]);
    
        $formBuilder->setMethod('GET');
    

Controller / Action / Usage

  • namespace App\Controller;
    
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    
    class myController extends AbstractController {
    
        public function myAction(Request $request,
                                 FormFactoryInterface $formFactory
        ) {
            // With data class 'Foo' and options
            $form = $this->createForm(FooFormType::class, $foo, [
                'myOption' => 'some value',
            ]);
    
            $form->handleRequest($request);
    
            return $this->renderForm('myTemplate.html.twig', [
                'form' => $form,
            ]);
    
        }
    
    }

 

Do not clear missing fields

We have a form object and set some defaults, then we create the form with it.

Does not work because it clears missing fields:

  • $form->handleRequest($request);

Use instead:

  • $form->submit($request->get($form->getName()), false);

 

Use custom prefix or without prefix / form name

With custom form name / prefix

If set to empty string '' -> <input name="first_name"> instead of <input name="foo[first_name]">

  • use Symfony\Component\Form\FormFactoryInterface;
    
    public function myAction(Request $request, FormFactoryInterface $formFactory ) {
    
        $form = $this->formFactory->createNamed('', FooType::class);
    }

Wishlist

  • Allow to change values in bound form (e.g. update "offset" pagination field)
  • Allow to set form name (field prefix) in config:
    •     public function configureOptions(OptionsResolver $resolver)
          {
              $resolver->setDefaults([
                  'name' => 'my_prefix',
    • Renders: <input name="my_prefix[first_name]">
  • Support 'placeholder' option in all suitable form field types (like in ChoiceType)
  • Form Twig functions are cumbersome for custom attributes like CSS classes -> no IDE autocompletion e.g. for Bootstrap
  • Allow to get the form as http url / query similar to JS
    • new URLSearchParams(newFormData(formElement))
    • or PHP http_build_query()
      • $form->getHttpParams()