Symfony2无法加载类型EntityType


Symfony2 Could not load type EntityType

尝试在Symfony2表单类型中创建EntityType字段时遇到问题。

这是Symfony2手册中官方EntityType参考的一段代码:

use Symfony'Bridge'Doctrine'Form'Type'EntityType; 
...
$builder->add('users', EntityType::class, array(
        'class' => 'AppBundle:User',
        'choice_label' => 'username',
    ));

回到浏览器,我得到了Could not load type "Symfony'Bridge'Doctrine'Form'Type'EntityType"错误。

EntityType类存在于给定的命名空间中。

我需要为这个字段类型获得一些传统的扩展吗?

您使用的是什么版本的Symfony?

这个FooBarType::class在Symfony 2.8和3.x中是新的,旧版本不支持它。试着用'entity'替换EntityType::class,看看它是否有效。当您升级到Symfony 2.8时,您可以使用FQCN,从3.x开始,这将是唯一的选择。

EntityType类不在公共Type类文件夹(Symfony'Component'Form'Extension'Core'Type')中,而是在Symfony'Bridge'Doctrine'Form'Type'

因此,如果您使用Symfony 3或Symfony 2.8和EntityType::class语法,则必须将

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