How to get form values in Symfony2 controller
I am using a login form on Symfony2 with the following controller code
public function loginAction(Request $request)
{
$user = new SiteUser();
$form = $this->createForm(new LoginType(), $user);
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
$data = $form->getValues();
// Need to do something with the data here
}
return $this->render('GDSiteBundle::header.html.twig', array('form' => $form->createView()));
}
But I am getting the following warning:
Warning: array_replace_recursive() [function.array-replace-recursive]: Argument #1 is not an array in \vendor\symfony\src\Symfony\Component\Form\Form.php line 593 500 Internal Server Error - ErrorException
Can someone help me understand whats incorrect, and how I can fix it? Thanks.
Update: The twig file is something like this:
<div class="form">
{{ form_errors(form) }}
<form action="{{ path('site_user_login') }}" method="POST" {{ form_enctype(form) }}>
<div class="level1">
{{ form_row(form.username) }}
<a href="javascript:void(0)" id="inscription">{% trans %}Registration{% endtrans %}</a>
</div>
<div class="level2">
{{ form_row(form.pwd_hash) }}
<div class="forget_pass"><a href="#" id="frgt">{% trans %}Forgot Password ?{% endtrans %}</a></div>
</div>
<input type="submit" class="submit" name="login" value/>
<div class="clr"></div>
</form>
</div>
Here is the function in the Form's Type
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('username', 'text', array('label' => 'Username : '));
$builder->add('pwd_hash','password', array('label' => 'Password : '));
}
Here is the route:
site_user_login:
pattern: /{_locale}/login
defaults: {_controller: GDSiteBundle:SiteUser:login}
Simply :
$data = $form->getData();
None of the above worked for me. This works for me:
$username = $form["username"]->getData();
$password = $form["password"]->getData();
I hope it helps.
In Symfony 2 ( to be more specific, the 2.3 version ) you can get a data of an field by
$var = $form->get('yourformfieldname')->getData();
or you can get all data sent
$data = $form->getData();
where '$data' is an array containing your form fields' values.