我尝试使用一组带有额外文字输入的选项创建一个表单字段,如果您选择'其他'
,则需要填写这些输入。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
我已将choices
设置为{/ 1}}:
$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() ],
));
我如何获得'其他,请注明'选项按预期工作?
答案 0 :(得分:2)
在这种情况下,您需要创建自定义表单类型,它将是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的源代码。
答案 1 :(得分:-1)
这是我的数据转换器,可以为谁提供帮助
<?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;
}
}