It's not easy to do, but you can do it with a customs form type field and a Twig theme:
1.Create a new field type like ChoiceInputType
. That class should contain two field types, ChoiceType and 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 a twig theme on your new custom field type and organize it as you want.
{% block choiceInputType_widget %}
... custom here ...
{% endblock %}
3.Use your new ChoiceInputType
inside your form.
$builder->add(
'choiceInputType',
ChoiceInputType::class,
[
'mapped' => false,
'block_prefix' => 'choiceInputType',
'label' => false,
'choices' => [
'test 1' => 1,
'test 2' => 2,
'test 3' => 3,
]
]
);
Here some links to other questions similar to this thread that can help you: