扩展Doctrine2形式的EntityType

pza*_*zaj 1 php symfony doctrine-orm sonata-admin symfony2-forms

我正在寻找一种扩展Symfony 2 EntityType的方法

Symfony\Bridge\Doctrine\Form\Type\EntityType
Run Code Online (Sandbox Code Playgroud)

就像在延伸这一个的新类型中,没有创造FormTypeExtension- 而我无法弄明白.有谁知道这样做的正确方法?

我试过这样简单地扩展它:

class NestedEntityType extends EntityType {

    public function getName() {
        return $this->getBlockPrefix();
    }

    public function getBlockPrefix() {
        return 'nested_entity';
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在奏鸣曲管理课我有:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('types', NestedEntityType::class, [
        'label' => false,
        'multiple' => true,
        'expanded' => true,
        'by_reference' => false
    ]);
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是它会导致致命错误:

可捕获的致命错误:传递给Symfony\Bridge\Doctrine\Form\Type\DoctrineType :: __ construct()的参数1必须实现接口Doctrine\Common\Persistence\ManagerRegistry,没有给定,调用

我需要保留整个功能EntityType,除了一个例外 - 它的呈现方式.这就是为什么我需要扩展这种类型(我在其他领域使用它,所以我不能只为它修改模板!).

我正在使用Symfony 2.8(仅供记录).

Don*_*sto 7

您不应该直接扩展它,而是使用parent选项

/**
 * {@inheritdoc}
 */
public function getParent()
{
    return EntityType::class;
}
Run Code Online (Sandbox Code Playgroud)

所以像

class NestedEntityType extends AbstractType 
{

    public function getName() 
    {
        return $this->getBlockPrefix();
    }

    public function getBlockPrefix() 
    {
        return 'nested_entity';
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return EntityType::class;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,如果你扩展的FormType有注入(或设置)的东西到构造函数中,你不需要关心,因为symfony会为你做.