在Symfony中为我的ChoiceType表单字段添加"其他,请指定"选项

Bjo*_*orn 6 php symfony-forms symfony

我正在尝试使用一组带有额外文本输入的选项创建一个表单字段,如果您选择"其他",则需要填写这些输入:

How often do you exercise?
(*) I do not exercise at the moment 
( ) Once a month
( ) Once a week
( ) Once a day
( ) Other, please specify: [             ]
Run Code Online (Sandbox Code Playgroud)

目前,我正在使用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() ],
));
Run Code Online (Sandbox Code Playgroud)

如何获得"其他,请指定"选项以按预期工作?

Kam*_*nek 4

在这种情况下,您将需要创建自定义表单类型,它将是ChoiceType和的组合TextType。自定义表单类型的详细介绍可以找到 id 文档: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)
    {
        // 
    }

));
Run Code Online (Sandbox Code Playgroud)

请看一下:

我认为实现它的最佳方法是查看DateTimeType的源代码。