Creating a custom form field type in symfony 2

I am finally starting to dive into symfony 2 properly. Yes – it’s taken a while, work has taken me in different directions! I found myself needing to create a custom form field type pretty quickly, but couldn’t find much in the way of documentation to do so, so I thought I’ld throw it up here; partly to help others, but mostly to get feedback to make sure I’m not approaching this from the wrong angle.

I have a model called Person, and this Person has a attribute of preferredTranportMethod, which could be either Train, Car or Bike. This is similar to what one might use an enum for with doctrine, but for portability I’m making this an integer. This means my model looks something like this:

In a form I wan this to be a select box, so it was typical for me to do something like this in my form type:

The problem with this is that it’s not reusable – if I had several forms with this choice, and needed to add PLANE to the options, I’d have to modify them all. So, the solution was to add my own form field type of ‘transportmethod’

To start with, I looked at how the Timezone field type worked, looking at the source in

. It seemed pretty simple, take al ook at the code yourself. You’ll notice is separates out the choices into a separate class of TimezoneChoiceList. I copied this structure to create my transportmethod type in my own bundle.

In the file src/Acme/ProfileBundle/Form/Extension/Type/TransportMethodType.php

As you can see, this references TransportMethodChoiceList, which is in

Now I need to register this new field type as a service in my Bundle

Now in my form types, I can simply do:

Hope that helps! 🙂

11 thoughts on “Creating a custom form field type in symfony 2”

  1. Nice post! A small improvement: You can skip the TransportMethodChoiceList and directly set the “choices” option in TransportMethodType.

  2. Thanks, this helped me!
    I worked a little more on this and this is the yaml syntax to register the new type:

    class: AcmeProfileBundleFormExtensionTypeTransportMethodType
    – { name: form.type }

  3. I was trying this example and throw me this error

    Fatal error: Declaration of ProyectoActividadesBundleFormExtensionTypeTransportMethodType::getParent() must be compatible with that of SymfonyComponentFormFormTypeInterface::getParent() in /var/www/Symfony/src/Proyecto/ActividadesBundle/Form/Extension/Type/TransportMethodType.php

    In the form i’m using
    ->add(‘days’, ‘transportmethod’, array(
    ‘multiple’ => true,
    ‘property_path’ => false,))

    Any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *