Symfony 5 - 带有 TextType 的自定义 ChoiceType

Symfony 5 - Custom ChoiceType with TextType

在 Symfony 5 中,我在表单中有一个 ChoiceType,我有 2 个选择。我想在你可以写你想要的地方放一个“其他”的选择。 我尝试在选项中加入 TextType。

提前致谢

->add('projectType', ChoiceType::class,[
                'label' => 'Votre projet concerne : ',
                'choices' => [
                    'Maison' => 'Maison',
                    'Appartement' => 'Appartement',
                ]
            ])

你知道如何将 TextType 添加到我的 ChoiceType 吗?

这并不容易,但您可以使用海关表单类型字段和 Twig 主题来完成:

1.Create 一个新的字段类型,如 ChoiceInputType。 class 应该包含两种字段类型,ChoiceType 和 TextType。

/**
 * Class ChoiceInputType
 */
class ChoiceInputType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add(
                'choiceType',
                ChoiceType::class,
                [
                    'required' => false,
                    'choices'  => $options['choices'],
                    'label' => 'Make your choice...',
                ]
            )
            ->add(
                'choiceInput',
                TextType::class,
                [
                    'required' => false,
                    'label'    => false,
                    'attr'     => [
                        'placeholder' => 'Other choice...',
                    ],
                ]
            );
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['choices'] = $options['choices'];
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setRequired(['choices']);

        $resolver->setDefaults(
            [
                'choices' => [],
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'choiceInputType';
    }
}

2.Create 在您的新自定义字段类型上添加 twig theme 并根据需要进行组织。

{% block choiceInputType_widget %}
    ... custom here ...
{% endblock %}

3.Use 您的新 ChoiceInputType 在您的表单中。

$builder->add(
     'choiceInputType',
     ChoiceInputType::class,
         [
            'mapped'  => false,
            'block_prefix' => 'choiceInputType',
            'label'   => false,
            'choices' => [
                'test 1' => 1,
                'test 2' => 2,
                'test 3' => 3,
             ]
          ]
  );

这里有一些与此线程类似的其他问题的链接可以帮助您:

  • Customize the rendering of a choice/entity field in Symfony2