Добавление опции «другой, пожалуйста, укажите» в поле формы ChoiceType в 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: [ ] 

В настоящее время я использую ChoiceType где я 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() ], )); 

Как я могу использовать параметр «другой, пожалуйста, укажите», чтобы он работал, как ожидалось?

В этом случае вам нужно будет создать собственный тип формы, который будет сочетать ChoiceType и TextType . Хорошее введение в пользовательские формы может быть найдено 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) { // } )); 

Пожалуйста, взгляните на:

Я думаю, что лучший способ добиться этого – взглянуть на исходный код DateTimeType .

Вот мои данныеTransformer, для кого кто может помочь

 <?php namespace AppBundle\Form\Type; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; class ChoiceToTextTransformer implements DataTransformerInterface { private $em; /** * ChoiceToTextTransformer constructor. * @param EntityManagerInterface $em */ function __construct(EntityManagerInterface $em) { $this->em = $em; } public function transform($values) { if (!$values) return array(); $array = array(); foreach ($values as $value) { list($id, $type) = explode("_", $value); $array[] = $this->em->getRepository('AppBundle:' . $type)->find($id); } return $array; } public function reverseTransform($values) { if ($values === null) return array(); $choices = array(); foreach ($values as $object) { $choices[] = array_filter($choices); } foreach ($values as $key => $value){ if (!$value == null){ dump($value); return $value; } } return $value; } }