【问题标题】:Access session from formType in Symfony2从 Symfony2 中的 formType 访问会话
【发布时间】:2012-12-01 02:38:23
【问题描述】:

我正在尝试将会话数据放入我的表单中,但我不知道该怎么做。

我可以将它传递给我的 FormType 的构造函数,但实际使用会话的 FormType 在主窗体中嵌套更深 3 层。 所以我认为像这样在每种表单类型的每个构造函数中传递会话对象是很脏的:

->add('name', new NestedFormType($this->session))

我还考虑过使用 formsType 作为服务。所以我会为每个应该注入会话的表单类型都有一个父级。

但是如果不将我所有的表单定义为服务,我该怎么做呢?

此外,我无法访问我的 FormTypes 中的DIC。因此,可以创建第一个 formType 对象(在可以访问 DIC 的控制器中创建),但是嵌套的 FormTypes 不能从它们的父级实例化。

有干净的解决方案吗?

【问题讨论】:

    标签: php symfony dependency-injection symfony-2.1


    【解决方案1】:

    您需要将此父表单定义为服务并将会话作为参数传递。

    看这个问题:Create a form as a service in Symfony2

    【讨论】:

    • 我想过,但是如果他们的父对象是服务但他们不是,我应该如何创建子对象?
    • 我认为你可以在选项参数中传递你想要形成构造函数的所有数据:)
    • 也许吧,但我必须将它从一个表单传递到另一个表单,直到我达到我需要会话的表单
    • 所以忘记父母。只需将嵌入表单创建为服务并以这种方式进行:)
    【解决方案2】:

    您不需要为更高级别的表单类型定义服务,只要您通过别名引用内部注入的表单类型即可:

    NestedFormType 服务定义:

    nested.form.type:
        class: Type\NestedFormType
        tags:
            - { name: form.type, alias: nested_form }
        arguments: [ @security.context ]
    

    NestedFormType:

    class NestedFormType extends AbstractType
    {
        private $security_context;
    
        public function __construct($security_context)
        {
            $this->security_context = $security_context;
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            // do something with $this->security_context
        }
    
        public function getName()
        {
            return 'nested_form';
        }
    }
    

    父窗体类型:

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('name', 'nested_form'); 
        // 'nested_form' matches service definition and NestedFormType::getName()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 2011-11-03
      • 2015-11-05
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多