2014-01-09 49 views
0

我正在使用FOSUserBundle並覆蓋了RegistrationController。當表格提交併且有效時,我想要獲取用戶在註冊表中輸入的電子郵件地址。如何從FOSUserBundle註冊表單獲取表單數據?

但我看不出有什麼辦法得到它。由於從Symfony2 forms documentation拍攝,你可以得到表單數據是這樣的:

$this->get('request')->request->get('name'); 

RegistrationController不知道get()方法(因爲它不是從Symfony2的控制器實體繼承)。所以我可以這樣做:

// Note the ...->container->... 
$this->container->get('request')->request->get('name'); 

但是,這返回NULL。現在我試着從$form得到它。

// Does contain a lot of stuff, but not the entered email address 
$form->get('email'); 

// Does also contain a lot of stuff, but not the desired content 
$request->get('email'); 
$request->request('email'); 

// Throws error message: No method getData() 
$request->getData(); 

任何想法?

回答

2

這真的很簡單。你創建一個與相關實體的表單。在FOSUserBundle你應該有一個RegistrationFormHandler,並在process方法你有:

$user = $this->createUser(); 
$this->form->setData($user); 
if ('POST' === $this->request->getMethod()) { 
    $this->form->bind($this->request); 
    if ($this->form->isValid()) /**(...)**/ 

$user對象的每個值由表格數據覆蓋的線$this->form->bind($this->request)後。所以你可以使用$user->getEmail()

另一方面,您可以直接從請求中獲取數據,但不能通過屬性名稱,而是通過表單名稱獲取數據。在FOSUserBundle註冊表中,它被稱爲fos_user_registration - 您可以在FOS/UserBundle/Form/Type/RegistrationFormType.phpgetName方法中找到它。

$registrationArray = $request->get('fos_user_registration'); 
$email = $registrationArray['email']; 
+0

做到了!謝謝! –

1

如果你使用控制器作爲服務(該服務應與這方面的工作),你可以通過RequestStack(SF> = 2.4)在構造函數中做$this->request_stack->getCurrentRequest()->get();

你可以通過把它

我的猜測是您正在嘗試獲取POST數據。您正在嘗試將數據放入我想要的表單對象中。如果您有自定義表單,我會建議您查看:http://symfony.com/doc/current/book/forms.html

至於你的問題,表格可能包含一個名稱。如果您想直接訪問它,而不是在表單中執行操作,則需要直接通過$ deep,get('registration_form_name[email]', null, true);處的真實數據獲取它。您還可以執行$email = $request->get('registration_form_name')['email'];(如果您有php 5.4+)

+0

很難選擇接受你的答案或Piotrs,所以我支持與較低的代表答覆者。我非常抱歉,非常感謝! –