将entityManager传递给EntityType类

时间:2017-05-20 14:21:35

标签: symfony entitymanager

使用Symfony 3.2,我会通过构造函数将entityManager对象传递给EntityType类。

我发现它可以使用服务完成,如下面的配置:

config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }
    - { resource: "@mybundle/Resources/config/services.yml" }

services.yml

services:
    mybundle.profile_key:
        class: App\Bundle\mybundle\Form\ProfileKeyType
        arguments: ["@doctrine.orm.entity_manager"]

我的实体类型:

namespace App\Bundle\mybundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Doctrine\ORM\EntityManager;

class ProfileKeyType extends AbstractType
{

    private $em;
    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('key', TextType::class, array(
                "label" => "Chiave identificativa"
        ))->add('visible', CheckboxType::class, array(
                'label' => "Default visible",
                "label_attr" => array( 'title' => 'Imposta la visibilità di default di questa chiave' ),
                'required' => true
        ))->add('entity', CollectionType::class, array(
                "data_class" => Entity::class
        ))->add('property')->add('type');
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'App\Bundle\mybundle\Entity\ProfileKey'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'app_bundle_mybundle_profilekey';
    }


}

当我浏览插入页面时,我收到此错误:

Type error: Argument 1 passed to App\Bundle\myBundle\Form\ProfileKeyType::__construct() must be an instance of Doctrine\ORM\EntityManager, none given, called in D:\eclipse_neon_workspace\iSerPa\vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 85

怎么了?

提前谢谢

2 个答案:

答案 0 :(得分:2)

创建表单时,您可以这样做:

// inside controller action
// $em is the required EntityManager instance
$em = $this->getDoctrine()->getEntityManager();
$form = $this->createForm(new ProfileKeyType($em), $profileKey);

答案 1 :(得分:0)

您应该将form.type标记添加到服务定义中,如下所示:

services:
serpabackend.profile_key:
    class: App\Bundle\mybundle\Form\ProfileKeyType
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: form.type }