问题
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