2012-12-13 80 views
1

我試圖將會話數據導入到我的表單中,但我不知道該怎麼做。在Symfony2中從formType訪問會話

我可以將它傳遞給我的FormType的構造函數,但實際使用會話的FormType是在主窗體中嵌套3個級別更深。 所以我認爲這是骯髒的傳遞會話對象在這樣每個窗體類型的每個構造函數:

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

我也想過用formsType的服務。所以我會爲每個應該與會話注入的formType有一個父級。

但我怎麼能沒有defininf我所有的表格作爲服務

此外,我無法訪問我的FormTypes中的DIC。因此,可以創建第一個formType對象(在控制器中創建該對象,該對象可以訪問DIC),但嵌套的FormType不能與其父級交互。

是否有乾淨的解決方案?

回答

1

您需要將此父窗體定義爲服務並將會話作爲參數傳遞。

看看這個問題:

NestedFormType服務:Create a form as a service in Symfony2

+0

我想過,但我應該如何創建子對象,如果他們的父母是服務,但他們不是? – Leto

+0

我認爲你可以傳遞所有數據你想要在選項參數中構造構造函數:) –

+0

也許,但我必須將它從表單傳遞到窗體,直到我到達需要會話的窗體 – Leto

0

你並不需要,只要你指的是內爲你更高級別的表單類型定義服務,通過它的別名注射形式類型定義:

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

ParentFormType:

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