Symfony2: Access the container in the repository

后端 未结 2 1211
遇见更好的自我
遇见更好的自我 2020-12-19 19:38

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

2条回答
  •  一向
    一向 (楼主)
    2020-12-19 19:59

    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

提交回复
热议问题