可捕获致命错误:传递给“...\FormType::__construct()”的第一个参数必须实现接口

6

我正在尝试在formType中调用entityManager,但不知道为什么它无法正常工作。

FormType

private $manager;

public function __construct(ObjectManager $manager)
{
    $this->manager = $manager;
}

控制器:

$form = $this->createForm(ProductsType::class, $products);

服务:

apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type }

错误:

可捕获的致命错误: MyBundle\Form\FormType::__construct() 的参数1必须实现 Doctrine\Common\Persistence\ObjectManager 接口,但未给出任何参数,调用位置为 vendor/symfony/symfony/src/Symfony/Component/Form/FormRegistry.php 的第90行,定义位置为xxx


你的代码看起来没问题。我猜测你没有加载services.yml文件。你能否从services.yml文件访问其他服务?使用bin/console container :: debug验证服务是否存在。同时检查ProductsType和ProductType之间的差异,事实上,拼写很可能是问题所在。 - Cerad
4个回答

3
假设您的services.yml文件已经被加载,并且您复制并粘贴了内容,那么您可能有一个简单的拼写错误:
# services.yml
class: ApxDev\UsersBundle\Form\ProductType
should be
class: ApxDev\UsersBundle\Form\ProductsType

1

让我们来看看你的错误

传递给 MyBundle\Form\FormType::__construct() 的第一个参数

因此,当你实例化 FormType 时,我们正在谈论你传递的参数,如下所示

$form = new \MyBundle\Form\FormType($somearg);

您的定义说:
public function __construct(ObjectManager $manager)

根据错误的第二部分

必须实现接口Doctrine\Common\Persistence\ObjectManager

很明显,ObjectManager是一个接口。这意味着您必须在注入到类中的对象中实现该接口,因为这是您告诉PHP要求的。具体做法如下:

class Something implements \Doctrine\Common\Persistence\ObjectManager {
    // Make sure you define whatever the interface requires within this class
}
$somearg = new Something();
$form = new \MyBundle\Form\FormType($somearg);

不是的。他正在定义表单类型作为一个服务,这个服务将负责注入:http://symfony.com/doc/2.8/cookbook/form/create_custom_field_type.html#creating-your-field-type-as-a-service - Cerad

1
你已将表单定义为一个服务(在services.yml中),但是你没有使用它作为一个服务。你应该使用service container来创建表单,而不是使用createForm,因此需要更改以下代码:
$form = $this->createForm(ProductsType::class, $products);

转换为:

$form = $this->get('apx.form.type.product')

并阅读有关将表单定义为服务的更多信息


不行:在S2.8/S3中有所改变:http://symfony.com/doc/2.8/cookbook/form/create_custom_field_type.html#creating-your-field-type-as-a-service - Cerad

0

在services.yml中尝试:

apx.form.type.product:
    class: ApxDev\UsersBundle\Form\ProductType
    arguments: 
        - '@doctrine.orm.entity_manager'
    tags:
        - { name: form.type }

Symfony 3.4


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接