[英]Access session from formType in Symfony2
I'm trying to get session data into my forms but i don't know how to do. 我正在尝试将会话数据放入表单,但是我不知道该怎么办。
I could pass it to the constructor of my FormType but the FormType that actually use the session is nested 3 levels deeper in the main form. 我可以将其传递给FormType的构造函数,但实际使用该会话的FormType在主表单中嵌套了3个层次 。 So i think that it is dirty to pass the session object in each constructor of each form type like this :
所以我认为在这样的每种表单类型的每个构造函数中传递会话对象都是很肮脏的:
->add('name', new NestedFormType($this->session))
I also thought about using formsType as service. 我还考虑过将FormsType用作服务。 So i would have a parent for each of my formsType that should be injected with session.
因此,我将为每个FormsType都添加一个父级,该父级应该与会话一起注入。
But how can i do that without defininf all my forms as services ? 但是,如果不将我的所有表格都定义为服务,该怎么办?
Futhermore, i can't access to the DIC
inside of my FormTypes. 此外,我无法访问FormTypes内部的
DIC
。 So, it's ok for the creation of the first formType object (which is created in the controller which can access to DIC
) but the nested FormTypes cannot be instianciated from their parent. 因此,可以创建第一个formType对象(在可以访问
DIC
的控制器中创建),但是不能从其父级实例化嵌套的FormType。
Is there a clean solution? 有没有干净的解决方案?
You need to define this parent form as a service and pass the session as the argument. 您需要将此父表单定义为服务,并将会话作为参数传递。
look at this question: Create a form as a service in Symfony2 看一下这个问题: 在Symfony2中将表单创建为服务
You don't need to define services for your higher level form types as long as you refer to the inner, injected form type by its alias: 您不需要为更高级别的表单类型定义服务,只要您通过别名引用内部注入的表单类型即可:
NestedFormType service definition: NestedFormType服务定义:
nested.form.type:
class: Type\NestedFormType
tags:
- { name: form.type, alias: nested_form }
arguments: [ @security.context ]
NestedFormType: 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';
}
}
ParentFormType: ParentFormType:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('name', 'nested_form');
// 'nested_form' matches service definition and NestedFormType::getName()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.