Symfony comes with a bunch of core field types available for building forms. However there are situations where we want to create a custom form field type for a specific purpose. This recipe assumes we need a field definition that holds a person's gender, based on the existing choice field. This section explains how the field is defined, how we can customize its layout and finally, how we can register it for use in our application.

Defining the Field Type

In order to create the custom field type, first we have to create the class representing the field. In our situation the class holding the field type will be called GenderType and the file will be stored in the default location for form fields, which is <BundleName>\Form\Type. Make sure the field extends AbstractType:
为了创建自定义域类型,首先我们需要创建该域对应的类。就我们这种情况而言,我们可以将保持域类型的类定义为GenderType,并将该文件放置在表单域的缺省位置:<BundleName>\Form\Type 目录中,并确保该表单域从AbstractType类扩展:

  1. // src/Acme/DemoBundle/Form/Type/GenderType.php 
  2. namespace Acme\DemoBundle\Form\Type; 
  4. use Symfony\Component\Form\AbstractType; 
  5. use Symfony\Component\OptionsResolver\OptionsResolverInterface; 
  7. class GenderType extends AbstractType 
  8.     public function setDefaultOptions(OptionsResolverInterface $resolver
  9.     { 
  10.         $resolver->setDefaults(array
  11.             'choices' => array
  12.                 'm' => 'Male'
  13.                 'f' => 'Female'
  14.             ) 
  15.         )); 
  16.     } 
  18.     public function getParent() 
  19.     { 
  20.         return 'choice'
  21.     } 
  23.     public function getName() 
  24.     { 
  25.         return 'gender'
  26.     } 
The location of this file is not important - the Form\Type directory is just a convention.

Here, the return value of the getParent function indicates that we're extending the choice field type. This means that, by default, we inherit all of the logic and rendering of that field type. To see some of the logic, check out the ChoiceType class. There are three methods that are particularly important:

  • buildForm() - Each field type has a buildForm method, which is where you configure and build any field(s). Notice that this is the same method you use to setup your forms, and it works the same here.
    buildForm() - 每个域类型都有一个buildForm方法,在该方法中您可以配置和构建任何表单域。注意这与您设置您表单的方法相同,同时它们的工作原理也相同。
  • buildView() - This method is used to set any extra variables you'll need when rendering your field in a template. For example, in ChoiceType, a multiple variable is set and used in the template to set (or not set) the multiple attribute on the select field. See Creating a Template for the Field for more details.
    buildView() - 该方法用于设置您在模板中渲染您表单域所需的任何额外变量。例如,在ChoiceType中multiple变量被设置用来在模板中设置(或不设置)select表单域的multiple属性。详情请参见为表单域创建模板
  • setDefaultOptions() - This defines options for your form type that can be used in buildForm() and buildView(). There are a lot of options common to all fields (see form Field Type), but you can create any others that you need here.
    setDefaultOptions() - 该方法定义您表单类型的选项,可用于buildForm()和buildView()方法。对于全部表单域来说已经有很多常用选项(参见表单域类型),但您也可以在这里创建您所需的其它选项。
If you're creating a field that consists of many fields, then be sure to set your "parent" type as form or something that extends form. Also, if you need to modify the "view" of any of your child types from your parent type, use the finishView() method.

The getName() method returns an identifier which should be unique in your application. This is used in various places, such as when customizing how your form type will be rendered.

The goal of our field was to extend the choice type to enable selection of a gender. This is achieved by fixing the choices to a list of possible genders.

Creating a Template for the Field

Each field type is rendered by a template fragment, which is determined in part by the value of your getName() method. For more information, see What are Form Themes?.

In this case, since our parent field is choice, we don't need to do any work as our custom field type will automatically be rendered like a choice type. But for the sake of this example, let's suppose that when our field is "expanded" (i.e. radio buttons or checkboxes, instead of a select field), we want to always render it in a ul element. In your form theme template (see above link for details), create a gender_widget block to handle this:

  1. {# src/Acme/DemoBundle/Resources/views/Form/fields.html.twig #} 
  2. {% block gender_widget %} 
  3.     {% spaceless %} 
  4.         {% if expanded %} 
  5.             <ul {{ block('widget_container_attributes') }}> 
  6.             {% for child in form %} 
  7.                 <li> 
  8.                     {{ form_widget(child) }} 
  9.                     {{ form_label(child) }} 
  10.                 </li> 
  11.             {% endfor %} 
  12.             </ul> 
  13.         {% else %} 
  14.             {# just let the choice widget render the select tag #} 
  15.             {{ block('choice_widget') }} 
  16.         {% endif %} 
  17.     {% endspaceless %} 
  18. {% endblock %} 

Make sure the correct widget prefix is used. In this example the name should be gender_widget, according to the value returned by getName. Further, the main config file should point to the custom form template so that it's used when rendering all forms.

  1. # app/config/config.yml 
  2. twig: 
  3.     form: 
  4.         resources: 
  5.             - 'AcmeDemoBundle:Form:fields.html.twig' 

Using the Field Type

You can now use your custom field type immediately, simply by creating a new instance of the type in one of your forms:

  1. // src/Acme/DemoBundle/Form/Type/AuthorType.php 
  2. namespace Acme\DemoBundle\Form\Type; 
  4. use Symfony\Component\Form\AbstractType; 
  5. use Symfony\Component\Form\FormBuilderInterface; 
  7. class AuthorType extends AbstractType 
  8.     public function buildForm(FormBuilderInterface $builderarray $options
  9.     { 
  10.         $builder->add('gender_code'new GenderType(), array
  11.             'empty_value' => 'Choose a gender'
  12.         )); 
  13.     } 

But this only works because the GenderType() is very simple. What if the gender codes were stored in configuration or in a database? The next section explains how more complex field types solve this problem.

Creating your Field Type as a Service

So far, this entry has assumed that you have a very simple custom field type. But if you need access to configuration, a database connection, or some other service, then you'll want to register your custom type as a service. For example, suppose that we're storing the gender parameters in configuration:

  1. # app/config/config.yml 
  2. parameters: 
  3.     genders: 
  4.         m: Male 
  5.         f: Female 

To use the parameter, we'll define our custom field type as a service, injecting the genders parameter value as the first argument to its to-be-created __construct function:

  1. # src/Acme/DemoBundle/Resources/config/services.yml 
  2. services: 
  3.     form.type.gender: 
  4.         class: Acme\DemoBundle\Form\Type\GenderType 
  5.         arguments: 
  6.             - "%genders%" 
  7.         tags: 
  8.             - { name: form.type, alias: gender } 
Make sure the services file is being imported. See Importing Configuration with imports for details.

Be sure that the alias attribute of the tag corresponds with the value returned by the getName method defined earlier. We'll see the importance of this in a moment when we use the custom field type. But first, add a __construct argument to GenderType, which receives the gender configuration:

  1. // src/Acme/DemoBundle/Form/Type/GenderType.php 
  2. namespace Acme\DemoBundle\Form\Type; 
  4. use Symfony\Component\OptionsResolver\OptionsResolverInterface; 
  6. // ... 
  8. class GenderType extends AbstractType 
  9.     private $genderChoices
  11.     public function __construct(array $genderChoices
  12.     { 
  13.         $this->genderChoices = $genderChoices
  14.     } 
  16.     public function setDefaultOptions(OptionsResolverInterface $resolver
  17.     { 
  18.         $resolver->setDefaults(array
  19.             'choices' => $this->genderChoices, 
  20.         )); 
  21.     } 
  23.     // ... 

Great! The GenderType is now fueled by the configuration parameters and registered as a service. And because we used the form.type alias in its configuration, using the field is now much easier:

  1. // src/Acme/DemoBundle/Form/Type/AuthorType.php 
  2. namespace Acme\DemoBundle\Form\Type; 
  4. use Symfony\Component\Form\FormBuilderInterface; 
  6. // ... 
  8. class AuthorType extends AbstractType 
  9.     public function buildForm(FormBuilderInterface $builderarray $options
  10.     { 
  11.         $builder->add('gender_code''gender'array
  12.             'empty_value' => 'Choose a gender'
  13.         )); 
  14.     } 

Notice that instead of instantiating a new instance, we can just refer to it by the alias used in our service configuration, gender. Have fun!