不要将扩展表单类型重新声明为服务以传递父参数



我创建了一种对称形式类型,我希望在其中使用实体管理器。

因此,我将其宣布为Symfony文档中提到的服务:http://symfony.com/doc/current/form/form_depperencies.html#define-your-form-as-a-service

现在,我想创建另一种表单类型,以扩展第一种类型。但是,似乎我也需要将这种新表单类型声明为服务,即使它是从已经声明为服务的第一个类型延伸的。

是否可以告诉Symfony检测新表单正在扩展第一个表单类型并自动注入父类的依赖性?

// src/AppBundle/Form/TaskType.php
use DoctrineORMEntityManager;
class TaskType extends AbstractType
{
    private $em;
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...
    }
    // ...
}
// src/AppBundle/Form/TaskObject1Type.php
use DoctrineORMEntityManager;
class TaskObject1Type extends TaskType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        // ...
    }
    // ...
}

您不应通过扩展类扩展表单类型。相反,使用应使用getParent方法指向父类型。

所以,而是

class ChildType extends ParentType
{
    ...
}

使用

class ChildType extends AbstractType
{
    ...
    public function getParent()
    {
        return ParentType::class;
    }
}

因此,您需要处理父级依赖项。

最新更新