Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: Access the container in the repository

Tags:

symfony

I'm trying to show an user oriented choice list in a form and I don't manage to access to the container to get the current User.

I don't see how to get it in the Repository neither than in the Type.

Any Idea?

like image 776
Julien Ducro Avatar asked Dec 28 '25 06:12

Julien Ducro


2 Answers

Let say you created a FormType class. You don't know how to pass the container in this object.

Create now your own type extended from FormType and pass the container through the constructor

class MyType extends FormType
{
    private $container;

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

In your config.yml, define your new type

mytype:
  class: ...\MyType
  arguments: ["@service_container"]
  tags:
      - { name: form.type }

Now, use MyType instead of FormType in all your controllers

like image 94
Reuven Avatar answered Dec 31 '25 00:12

Reuven


Perhaps you can request the User object in the controller, and pass it on to the repository in the constructor?

like image 36
Dieter Avatar answered Dec 30 '25 23:12

Dieter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!