如何在我的EntityType表单中使用doctrine

时间:2017-09-22 09:36:51

标签: forms symfony doctrine

class AnalisiType extends AbstractType {

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

        if($options['data']->getIdProprietario()==NULL){
            $data_proprietario='';
        }else{
            $data_proprietario=$options['data']->getIdProprietario();
        }
 $em = $this->getDoctrine()->getEntityManager();
        $builder   ->add('idProprietario', EntityType::class, array(
                'label' => false,

                'placeholder' => 'Seleziona Anagrafica se presente',
                'class' => 'AppBundle:anagrafica',
                'query_builder' => function (anagraficaRepository $er ) {

                    return $er->createQueryBuilder('u')
                ->where('u.idTipologia = 1');
                },
                'choice_label' => 'ragione_sociale',
                        'data'=>$em->getReference("AppBundle:anagrafica",$options['data']->getIdProprietario()->getId())    ,

                'attr' => array(
                    'class' => 'chosen-select'
                ),
            ))

我的目标是在编辑表单中设置默认数据。在论坛中搜索我发现

'data'=> $ em-> getReference(“AppBundle:anagrafica”,$ options ['data'] - > getIdProprietario() - > getId()),

是正确的语法,但我不明白如何在表单中使用doctrine。 这种形式总是给我错误

Attempted to call an undefined method named "getDoctrine" of class "AppBundle\Form\AnalisiType"

我需要添加使用??????

我唯一的解决方案是创建服务吗?

我的services.yml

了解有关服务,参数和容器的更多信息

http://symfony.com/doc/current/service_container.html

参数:     #parameter_name:value

services:
    #service_name:
    #    class: AppBundle\Directory\ClassName
    #    arguments: ['@another_service_name', 'plain_value', '%parameter_name%']

1 个答案:

答案 0 :(得分:1)

如果您使用的是Symfony 2.8,则必须将表单定义为服务并注入EntityManger:

services:
    form:
        class: YourBundle\Form\Type\YourType
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
            - { name: form.type }

如果您使用的是Symfony 3.3,那么您的表单已经是一项服务,您只需在构造中键入提示EntityManagerInterface:

private $entityManager;

public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
}

还要确保您已在3.3中启用了自动配置,否则您必须将表单注册为服务:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository}'

    AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller'
        public: true
        tags: ['controller.service_arguments']