Adding a 'other, please specify' option to my ChoiceType form field in Symfony

大憨熊 提交于 2019-12-21 05:02:58

问题


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: [             ]

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?


回答1:


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

This should be something similar to:

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)
    {
        // 
    }

));

Please take a look at:

  • chapter about data transformers: http://symfony.com/doc/current/form/data_transformers.html
  • dynamic form modifications: http://symfony.com/doc/current/form/dynamic_form_modification.html

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




回答2:


Here's My dataTransformer for whom who may help

<?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;

}
}


来源:https://stackoverflow.com/questions/39115490/adding-a-other-please-specify-option-to-my-choicetype-form-field-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!