How to Create a Custom Form Field Type

Symfony comes with tens of form types (called “form fields” in other projects) ready to use in your applications. However, it’s common to create custom form types to solve specific purposes in your projects.

Creating Form Types Based on Symfony Built-in Types

The easiest way to create a form type is to base it on one of the existing form types. Imagine that your project displays a list of “shipping options” as a <select> HTML element. This can be implemented with a ChoiceType where the choices option is set to the list of available shipping options.

However, if you use the same form type in several forms, repeating the list of choices every time you use it quickly becomes boring. In this example, a better solution is to create a custom form type based on ChoiceType. The custom type looks and behaves like a ChoiceType but the list of choices is already populated with the shipping options so you don’t need to define them.

Form types are PHP classes that implement FormTypeInterface, but you should instead extend from AbstractType, which already implements that interface and provides some utilities. By convention they are stored in the src/Form/Type/ directory:

// src/Form/Type/ShippingType.php
namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ShippingType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choices' => [
                'Standard Shipping' => 'standard',
                'Expedited Shipping' => 'expedited',
                'Priority Shipping' => 'priority',
            ],
        ]);
    }

    public function getParent()
    {
        return ChoiceType::class;
    }
}

The configureOptions() method, which is explained later in this article, defines the options that can be configured for the form type and sets the default value of those options.

The getParent() method defines which is the form type used as the base of this type. In this case, the type extends from ChoiceType to reuse all of the logic and rendering of that field type.

Note

The PHP class extension mechanism and the Symfony form field extension mechanism are not the same. The parent type returned in getParent() is what Symfony uses to build and manage the field type. Making the PHP class extend from AbstractType is only a convenience way of implementing the required FormTypeInterface.

Now you can add this form type when creating Symfony forms:

// src/Form/Type/OrderType.php
namespace App\Form\Type;

use App\Form\Type\ShippingType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('shipping', ShippingType::class)
        ;
    }

    // ...
}

That’s all. The shipping form field will be rendered correctly in any template because it reuses the templating logic defined by its parent type ChoiceType. If you prefer, you can also define a template for your custom types, as explained later in this article.

Creating Form Types Created From Scratch

Some form types are so specific to your projects that they cannot be based on any existing form types because they are too different. Consider an application that wants to reuse in different forms the following set of fields as the “postal address”:

As explained above, form types are PHP classes that implement FormTypeInterface, although it’s more convenient to extend instead from AbstractType:

// src/Form/Type/PostalAddressType.php
namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PostalAddressType extends AbstractType
{
    // ...
}

When a form type doesn’t extend from another specific type, there’s no need to implement the getParent() method (Symfony will make the type extend from the generic FormType, which is the parent of all the other types).

These are the most important methods that a form type class can define:

buildForm()
It adds and configures other types into this type. It’s the same method used when creating Symfony form classes.
buildView()
It sets any extra variables you’ll need when rendering the field in a template.
configureOptions()
It defines the options configurable when using the form type, which are also the options that can be used in buildForm() and buildView() methods.
finishView()
When creating a form type that consists of many fields, this method allows to modify the “view” of any of those fields. For any other use case, it’s recommended to use instead the buildView() method.

Defining the Form Type

Start by adding the buildForm() method to configure all the types included in the postal address. For the moment, all fields are of type TextType:

// src/Form/Type/PostalAddressType.php
namespace App\Form\Type;

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

class PostalAddressType extends AbstractType
{
    // ...

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('addressLine1', TextType::class, [
                'help' => 'Street address, P.O. box, company name',
            ])
            ->add('addressLine2', TextType::class, [
                'help' => 'Apartment, suite, unit, building, floor',
            ])
            ->add('city', TextType::class)
            ->add('state', TextType::class, [
                'label' => 'State',
            ])
            ->add('zipCode', TextType::class, [
                'label' => 'ZIP Code',
            ])
        ;
    }
}

Tip

Run the following command to verify that the form type was successfully registered in the application:

1
$ php bin/console debug:form

This form type is ready to use it inside other forms and all its fields will be correctly rendered in any template:

// src/Form/Type/OrderType.php
namespace App\Form\Type;

use App\Form\Type\PostalAddressType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('address', PostalAddressType::class)
        ;
    }

    // ...
}

However, the real power of custom form types is achieved with custom form options (to make them flexible) and with custom templates (to make them look better).

Adding Configuration Options for the Form Type

Imagine that your project requires to make the PostalAddressType configurable in two ways:

  • In addition to “address line 1” and “address line 2”, some addresses should be allowed to display an “address line 3” to store extended address information;
  • Instead of displaying a free text input, some addresses should be able to restrict the possible states to a given list.

This is solved with “form type options”, which allow to configure the behavior of the form types. The options are defined in the configureOptions() method and you can use all the OptionsResolver component features to define, validate and process their values:

// src/Form/Type/PostalAddressType.php
namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PostalAddressType extends AbstractType
{
    // ...

    public function configureOptions(OptionsResolver $resolver)
    {
        // this defines the available options and their default values when
        // they are not configured explicitly when using the form type
        $resolver->setDefaults([
            'allowed_states' => null,
            'is_extended_address' => false,
        ]);

        // optionally you can also restrict the options type or types (to get
        // automatic type validation and useful error messages for end users)
        $resolver->setAllowedTypes('allowed_states', ['null', 'string', 'array']);
        $resolver->setAllowedTypes('is_extended_address', 'bool');

        // optionally you can transform the given values for the options to
        // simplify the further processing of those options
        $resolver->setNormalizer('allowed_states', static function (Options $options, $states) {
            if (null === $states) {
                return $states;
            }

            if (is_string($states)) {
                $states = (array) $states;
            }

            return array_combine(array_values($states), array_values($states));
        });
    }
}

Now you can configure these options when using the form type:

// src/Form/Type/OrderType.php
// ...

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('address', PostalAddressType::class, [
                'is_extended_address' => true,
                'allowed_states' => ['CA', 'FL', 'TX'],
                // in this example, this config would also be valid:
                // 'allowed_states' => 'CA',
            ])
        ;
    }

    // ...
}

The last step is to use these options when building the form:

// src/Form/Type/PostalAddressType.php
// ...

class PostalAddressType extends AbstractType
{
    // ...

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...

        if (true === $options['is_extended_address']) {
            $builder->add('addressLine3', TextType::class, [
                'help' => 'Extended address info',
            ]);
        }

        if (null !== $options['allowed_states']) {
            $builder->add('state', ChoiceType::class, [
                'choices' => $options['allowed_states'],
            ]);
        } else {
            $builder->add('state', TextType::class, [
                'label' => 'State/Province/Region',
            ]);
        }
    }
}

Creating the Form Type Template

By default, custom form types will be rendered using the form themes configured in the application. However, for some types you may prefer to create a custom template in order to customize how they look or their HTML structure.

First, create a new Twig template anywhere in the application to store the fragments used to render the types:

1
2
3
{# templates/form/custom_types.html.twig #}

{# ... here you will add the Twig code ... #}

Then, update the form_themes option to add this new template at the beginning of the list (the first one overrides the rest of files):

  • YAML
    1
    2
    3
    4
    5
    # config/packages/twig.yaml
    twig:
        form_themes:
            - 'form/custom_types.html.twig'
            - '...'
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    <!-- config/packages/twig.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <container xmlns="http://symfony.com/schema/dic/services"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:twig="http://symfony.com/schema/dic/twig"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            https://symfony.com/schema/dic/services/services-1.0.xsd
            http://symfony.com/schema/dic/twig
            https://symfony.com/schema/dic/twig/twig-1.0.xsd">
    
        <twig:config>
            <twig:form-theme>form/custom_types.html.twig</twig:form-theme>
            <twig:form-theme>...</twig:form-theme>
        </twig:config>
    </container>
    
  • PHP
    1
    2
    3
    4
    5
    6
    7
    // config/packages/twig.php
    $container->loadFromExtension('twig', [
        'form_themes' => [
            'form/custom_types.html.twig',
            '...',
        ],
    ]);
    

The last step is to create the actual Twig template that will render the type. The template contents depend on which HTML, CSS and JavaScript frameworks and libraries are used in your application:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{# templates/form/custom_types.html.twig #}
{% block postal_address_row %}
    {% for child in form.children|filter(child => not child.rendered) %}
        <div class="form-group">
            {{ form_label(child) }}
            {{ form_widget(child) }}
            {{ form_help(child) }}
            {{ form_errors(child) }}
        </div>
    {% endfor %}
{% endblock %}

The first part of the Twig block name (e.g. postal_address) comes from the class name (PostalAddressType -> postal_address). This can be controlled by overriding the getBlockPrefix() method in PostalAddressType. The second part of the Twig block name (e.g. _row) defines which form type part is being rendered (row, widget, help, errors, etc.)

The article about form themes explains the form fragment naming rules in detail. The following diagram shows some of the Twig block names defined in this example:

Caution

When the name of your form class matches any of the built-in field types, your form might not be rendered correctly. A form type named App\Form\PasswordType will have the same block name as the built-in PasswordType and won’t be rendered correctly. Override the getBlockPrefix() method to return a unique block prefix (e.g. app_password) to avoid collisions.

Passing Variables to the Form Type Template

Symfony passes a series of variables to the template used to render the form type. You can also pass your own variables, which can be based on the options defined by the form or be completely independent:

// src/Form/Type/PostalAddressType.php
use Doctrine\ORM\EntityManagerInterface;
// ...

class PostalAddressType extends AbstractType
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    // ...

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // pass the form type option directly to the template
        $view->vars['isExtendedAddress'] = $options['is_extended_address'];

        // make a database query to find possible notifications related to postal addresses (e.g. to
        // display dynamic messages such as 'Delivery to XX and YY states will be added next week!')
        $view->vars['notification'] = $this->entityManager->find('...');
    }
}

If you’re using the default services.yaml configuration, this example will already work! Otherwise, create a service for this form class and tag it with form.type.

The variables added in buildView() are available in the form type template as any other regular Twig variable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{# templates/form/custom_types.html.twig #}
{% block postal_address_row %}
    {# ... #}

    {% if isExtendedAddress %}
        {# ... #}
    {% endif %}

    {% if notification is not empty %}
        <div class="alert alert-primary" role="alert">
            {{ notification }}
        </div>
    {% endif %}
{% endblock %}