Inject Symfony EntityManager into Form Type via Services

后端 未结 3 1370
心在旅途
心在旅途 2021-01-13 21:59

I need to modify some fields in my form (label and class), based on whether the entity is the latest published version or not. So I need to be able to inject the entity mana

3条回答
  •  一个人的身影
    2021-01-13 22:16

    You got that error because you`re creating form type like this:

    $form = $this->createForm(new ViewType(), $view);
    

    You create new object ViewType without any arguments and it needs to be called with EntityManager. You can simply pass entity manager from controller, like this:

    $em = $this->get('doctrine.orm.entity_manager'); // or doctrine.orm.billing_entity_manager
    $form = $this->createForm(new ViewType($em), $view);
    

    In this case you don't even need to define this form type as a service.

    Use of doctrine.orm.entity_manager or doctrine.orm.billing_entity_manager depends on what you need to fetch inside ViewType - (from witch database).

    UPDATE:

    Define form type as a service.

    Add this two services to your configuration (services.yml):

    services
        gutensite_cms.form.view:
            factory_method: createNamed
            factory_service: form.factory
            class: Symfony\Component\Form\Form
            arguments:
                - view_form                        # name of the form
                - view                             # alias of the form type
                - null                             # data to bind, this is where your entity could go if you have that defined as a service
                - { validation_groups: [Default] } # validation groups
    
        gutensite_cms.form.type.view:
            class: Gutensite\CmsBundle\Form\Type\ViewType
            arguments: [ "@doctrine.orm.entity_manager" ]
            tags:
                - { name: form.type, alias: view }
    

    Then you can create new form by executing this inside your controller (or whatever has container) without manualy passing any arguments (they will be injected automaticly):

    public function newAction()
    {
        $view = ...;
        $form = $this->get( 'gutensite_cms.form.view' );
    
        // set initial form data if needed
        $form->setData( $view );
    }
    

提交回复
热议问题