How can I get the form data from the FOSUserBundle registration form?
-
21-12-2019 - |
Question
I am using the FOSUserBundle and have overwritten the RegistrationController
. When the form is submitted and valid, I want to get the email address the user entered in the registration form.
But I don't see any way to get it. As taken from the Symfony2 forms documentation, you can get form data like this:
$this->get('request')->request->get('name');
But the RegistrationController
does not know the get()
method (as it's not inherited from the Symfony2 controller entity). So I could go like this:
// Note the ...->container->...
$this->container->get('request')->request->get('name');
But this returns NULL
. Now I try to get it from the $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();
Any idea?
Solution
It's really, really simple. You create a form with related entity. In FOSUserBundle you should have a RegistrationFormHandler
, and in process
method you've got:
$user = $this->createUser();
$this->form->setData($user);
if ('POST' === $this->request->getMethod()) {
$this->form->bind($this->request);
if ($this->form->isValid()) /**(...)**/
After the line $this->form->bind($this->request)
every value in $user
object is overwritten by data from form. So you can use $user->getEmail()
.
On the other hand you are able to get data directly from request, but not by the property name, but by form name. In FOSUserBundle registration form it is called fos_user_registration
- you can find it in FOS/UserBundle/Form/Type/RegistrationFormType.php
in getName
method.
You get it by:
$registrationArray = $request->get('fos_user_registration');
$email = $registrationArray['email'];
OTHER TIPS
If you were to use Controller as a Service (which should work with this), you could pass the RequestStack (sf >=2.4) in the constructor and do $this->request_stack->getCurrentRequest()->get();
My guess is that you are trying to get the POST data. You are trying to put the data in a form object I presume. I would recommend you to take a look at: http://symfony.com/doc/current/book/forms.html if you have a custom form.
As regarding to your question, the form is probably containing a name. If you want to have direct access to it instead of doing things in your form, you need to fetch it multilevel if directly via the true at $deep, get('registration_form_name[email]', null, true);
You can also do $email = $request->get('registration_form_name')['email'];
(if you have php 5.4+)