symfony-forms Forms Create a custom form type


Example

A custom form type is a class which defines a reusable form component. Custom form components can be nested to create complicated forms.

Instead of creating a form in the controller using a form builder, you can use your own type to make the code more readable, reusable and maintanable.

Create a class which represents your form type

// src/AppBundle/Form/ExampleType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class ExampleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
             ->add('value', TextType::class, array('required' => false))
             ->add('number', NumberType::class)
             ->add('string', TextType::class)
             ->add('save', SubmitType::class)
        ;
    }
}

You can now use your form in controller:

use AppBundle\Form\ExampleType;

// ...

$form = $this->createForm(ExampleType::class, $data)