简体   繁体   English

在Symfony中为我的ChoiceType表单字段添加“其他,请指定”选项

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

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: 目前,我正在使用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() ],
));

How do I get the 'other, please specify' option to work as expected? 如何获得“其他,请指定”选项以按预期工作?

In this case you will need to create custom form type which will be combination of ChoiceType and TextType . 在这种情况下,您需要创建自定义表单类型,它将是ChoiceTypeTextType组合。 Nice intro to custom form types can be find id doc: http://symfony.com/doc/master/form/create_custom_field_type.html 自定义表单类型的简介可以找到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: 请看看:

I think the best way to achieve it is to take a look at the source code of the DateTimeType . 我认为实现它的最佳方法是查看DateTimeType的源代码。

Here's My dataTransformer for whom who may help 这是我的dataTransformer,可以为谁提供帮助

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

}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM