在 Symfony 中向我的 ChoiceType 表单字段添加“其他,请指定"选项 [英] Adding a 'other, please specify' option to my ChoiceType form field in Symfony

查看:24
本文介绍了在 Symfony 中向我的 ChoiceType 表单字段添加“其他,请指定"选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a form field with a set of choices with an extra text input which needs to be filled out if you choose '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 如下:

Currently, I'm using a ChoiceType where I have set my choices like this:

$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() ],
));

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

How do I get the 'other, please specify' option to work as expected?

推荐答案

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

In this case you will need to create custom form type which will be combination of ChoiceType and TextType. Nice intro to custom form types can be find id doc: 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)
    {
        // 
    }

));

请看:

我认为实现它的最好方法是查看 日期时间类型.

I think the best way to achieve it is to take a look at the source code of the DateTimeType.

这篇关于在 Symfony 中向我的 ChoiceType 表单字段添加“其他,请指定"选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆