Symfony 5-使用TextType自定义选择类型
在Symfony 5中,我有一个表单中的ChoiceType,有两个选项。我想把一个“其他”的选择,你可以写你想要的。 我尝试在选项中输入文本类型 提前谢谢Symfony 5-使用TextType自定义选择类型,symfony,symfony5,Symfony,Symfony5,在Symfony 5中,我有一个表单中的ChoiceType,有两个选项。我想把一个“其他”的选择,你可以写你想要的。 我尝试在选项中输入文本类型 提前谢谢 ->add('projectType', ChoiceType::class,[ 'label' => 'Votre projet concerne : ', 'choices' => [ 'Maison' =>
->add('projectType', ChoiceType::class,[
'label' => 'Votre projet concerne : ',
'choices' => [
'Maison' => 'Maison',
'Appartement' => 'Appartement',
]
])
您知道如何将文本类型添加到我的选择类型吗?这不容易,但您可以使用自定义表单类型字段和细枝主题: 1.创建一个新的字段类型,如
ChoiceInputType
。该类应包含两种字段类型,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.在新的自定义字段类型上创建一个字段,并根据需要组织它
{% block choiceInputType_widget %}
... custom here ...
{% endblock %}
3.在表单中使用新的选项InputType
$builder->add(
'choiceInputType',
ChoiceInputType::class,
[
'mapped' => false,
'block_prefix' => 'choiceInputType',
'label' => false,
'choices' => [
'test 1' => 1,
'test 2' => 2,
'test 3' => 3,
]
]
);
以下是一些与此线程类似的其他问题的链接,可以帮助您: