在 Symfony 中向我的 ChoiceType 表单字段添加 'other, please specify' 选项

Adding a 'other, please specify' option to my ChoiceType form field in Symfony

我正在尝试创建一个带有一组选项的表单字段,如果您选择 'other':

,则需要填写额外的文本输入
How often do you exercise?
(*) I do not exercise at the moment 
( ) Once a month
( ) Once a week
( ) Once a day
( ) Other, please specify: [             ]

目前,我正在使用 ChoiceType,其中我的 choices 设置如下:

$form->add('exercise', Type\ChoiceType::class, array(
    'label' => 'How often do you exercise?',
    'choices' => [ 'I do not excerise at the moment' => 'not', ... ],
    'expanded' => true,
    'multiple' => false,
    'required' => true,
    'constraints' => [ new Assert\NotBlank() ],
));

如何让 'other, please specify' 选项按预期工作?

在这种情况下,您将需要创建自定义表单类型,它将是 ChoiceTypeTextType 的组合。可以找到自定义表单类型的不错介绍:http://symfony.com/doc/master/form/create_custom_field_type.html

这应该类似于:

class ChoiceWithOtherType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // prepare passed $options

        $builder
            ->add('choice', Type\ChoiceType::class, $options)
            ->add('other', Type\TextType::class, $options)
        ;

        // this will requires also custom ModelTransformer
        $builder->addModelTransformer($transformer)

        // constraints can be added in listener
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            // ... adding the constraint if needed
        });

    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // if needed
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        // 
    }

));

请看:

我认为实现它的最佳方法是查看 DateTimeType.

的源代码