Symfony2:访问存储库中的容器 [英] Symfony2: Access the container in the repository

查看:27
本文介绍了Symfony2:访问存储库中的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在表单中显示面向用户的选择列表,但我无法访问容器以获取当前用户.

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.

我不知道如何在 Repository 和 Type 中获取它.

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

有什么想法吗?

推荐答案

假设您创建了一个 FormType 类.你不知道如何在这个对象中传递容器.

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

现在创建您自己的从 FormType 扩展的类型并通过构造函数传递容器

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;
    }
}

在你的 config.yml 中,定义你的新类型

In your config.yml, define your new type

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

现在,在所有控制器中使用 MyType 而不是 FormType

Now, use MyType instead of FormType in all your controllers

这篇关于Symfony2:访问存储库中的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆