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 class 存在于给定的命名空间中。

我需要为此字段类型获取一些额外的扩展名吗?

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

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

EntityType class 不在通用类型 classes 文件夹 (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;