如何使用expaned = true在EntityType中检查占位符

时间:2016-03-01 10:03:35

标签: php forms symfony radio-button

我正在使用EntityType

$builder
        ->add('defaultAnswer', EntityType::class, [
            'expanded' => true,
            'placeholder' => 'No default answer',
        ]);

显示无线电输入,但不检查占位符无线电输入。怎么做检查呢?

关于ChoiceType存在已关闭的问题:https://github.com/symfony/symfony/issues/15487,但我不想明确指定选择。

此外,占位符无线电输入不通过choice_attr回调函数。

2 个答案:

答案 0 :(得分:1)

您可以为EntityType创建一个扩展名,以转置选项'占位符'的值。选择:

namespace AppBundle\Form\Extensions;

use Symfony\Component\Form\AbstractTypeExtension;

use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class EntityExtension extends AbstractTypeExtension
{    
    public function configureOptions(OptionsResolver $resolver)
    {  
        $resolver->setDefault('choices',function(Options $options, $choices){
                    return array(''=>$options['placeholder'])+$choices;
                });
    }

    public function getExtendedType()
    {
        return EntityType::class;
    }
}

在service.yml中注册扩展名:

services:
    form_extension.entity:
        class: AppBundle\Form\Extensions\EntityExtension
        tags:
            - { name: form.type_extension, extended_type: Symfony\Bridge\Doctrine\Form\Type\EntityType }

答案 1 :(得分:0)

这应该适合你(占位符和empty_data):

        ->add('PetType', EntityType::class,  ['label' => 'Type of pet',
                                              'class' => 'AppBundle:PetType',
                                              'choice_label' => 'name',
                                              'placeholder'   =>'Choose pet type',
                                              'empty_data'  => null,