How Can I add get container in form builder symfony?

帅比萌擦擦* 提交于 2019-12-25 11:56:27

问题


How Can I add get container in form builder symfony ?

I would like use $get->container in form builder...


回答1:


Injecting the whole container into a form type is a bad practice. Please consider injecting only required dependencies to your form type. You can simply define your form type as a service and inject required dependencies.

src/AppBundle/Form/TaskType.php

use Doctrine\ORM\EntityManagerInterface;
// ...

class TaskType extends AbstractType
{
    private $em;

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

    // ...
}

src/AppBundle/Resources/config/services.yml

services:
    AppBundle\Form\TaskType:
        arguments: ['@doctrine.orm.entity_manager']
        tags: [form.type]

To inject a repository class there are two ways. The second approach is more clean.

Inject an EntityManager class and get repository class from EM:

$this->em->getRepository(User::class)

Register repository class as a service using EM factory and inject it to your form type:

  services:
    AppBundle\Repository\UserRepository:
      factory: ['@doctrine.orm.entity_manager', getRepository]
      arguments: ['AppBundle\Entity\User']



回答2:


One issue is to pass container as parameter to your FormType file from the controller:

$form_type = new MyFormType($this->container);

And add a construct method in your FormType file:

protected $container;

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

Then you can access to container by: '$this->container';

Hope it will help you ;)



来源:https://stackoverflow.com/questions/46415177/how-can-i-add-get-container-in-form-builder-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!