How to get form values in Symfony2 controller

FormsSymfony

Forms Problem Overview


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}

Forms Solutions


Solution 1 - Forms

Simply :

$data = $form->getData();

Solution 2 - Forms

None of the above worked for me. This works for me:

$username = $form["username"]->getData();
$password = $form["password"]->getData();

I hope it helps.

Solution 3 - Forms

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.

Solution 4 - Forms

In Symfony >= 2.3, you can get the value of single fields with:

$var = $form->get('yourformfieldname')->getData();

On the other hand, you can use:

$data = $form->getData();

BUT this would get you two different things:

  • the entity with values populated by the form, if your form have the data-class option enabled (so it's binded to an entity); this will exclude any field with the 'mapping' => false option

  • otherwise, an array with all the form's fields

Solution 5 - Forms

If you have extra fields in the form that not defined in Entity , $form->getData() doesn't work , one way could be this :

$request->get("form")["foo"] 

Or :

$form->get('foo')->getData();

Solution 6 - Forms

To get the data of a specific field,

$form->get('fieldName')->getData();

Or for all the form data

$form->getData();

Link to docs: https://symfony.com/doc/2.7/forms.html

Solution 7 - Forms

In Symfony forms, there are two different types of transformers and three different types of underlying data: enter image description here

In any form, the three different types of data are:

  • Model data

    This is the data in the format used in your application (e.g. an Issue object). If you call Form::getData() or Form::setData(), you're dealing with the "model" data.

  • Norm Data

    This is a normalized version of your data and is commonly the same as your "model" data (though not in our example). It's not commonly used directly.

  • View Data

    This is the format that's used to fill in the form fields themselves. It's also the format in which the user will submit the data. When you call Form::submit($data), the $data is in the "view" data format.

The two different types of transformers help convert to and from each of these types of data:

  • Model transformers:

    transform(): "model data" => "norm data"
    reverseTransform(): "norm data" => "model data"

  • View transformers:

    transform(): "norm data" => "view data"
    reverseTransform(): "view data" => "norm data"

Which transformer you need depends on your situation.

To use the view transformer, call addViewTransformer().


If you want to get all form data:

$form->getData();

If you are after a specific form field (for example first_name):

$form->get('first_name')->getData();

Solution 8 - Forms

I got it working by this:

if ($request->getMethod() == 'POST') {
    $username = $request->request->get('username');
    $password = $request->request->get('password');

    // Do something with the post data
}

You need to have the Request $request as a parameter in the function too! Hope this helps.

Solution 9 - Forms

I think that in order to get the request data, bound and validated by the form object, you must use this command :

$form->getViewData();
$form->getClientData(); // Deprecated since version 2.1, to be removed in 2.3.

Solution 10 - Forms

private function getFormDataArray($form)
{
    $data = [];
    foreach ( $form as $key => $value) {
        $data[$key] = $value->getData();
    }
    return $data;
}

Solution 11 - Forms

If you're using Symfony 2 security management, you don't need to get posted values, you only need to manage form template (see documentation).

If you aren't using Symfony 2 security management, I advise you strongly to use it. If you don't want to or if you can't, can you give us the LoginType's sources ?

Solution 12 - Forms

If Symfony 4 or 5, juste use this code (Where name is the name of your field):

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

Solution 13 - Forms

For not mapped form fields I use $form->get('inputName')->getViewData();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVishwaKumarView Question on Stackoverflow
Solution 1 - FormsHubert PerronView Answer on Stackoverflow
Solution 2 - FormspkoutView Answer on Stackoverflow
Solution 3 - FormsalbertView Answer on Stackoverflow
Solution 4 - FormsAlessandro LaiView Answer on Stackoverflow
Solution 5 - FormsSaman MohamadiView Answer on Stackoverflow
Solution 6 - FormsPJatelyView Answer on Stackoverflow
Solution 7 - FormsPmpr.irView Answer on Stackoverflow
Solution 8 - FormsVishwaKumarView Answer on Stackoverflow
Solution 9 - FormsChicnaView Answer on Stackoverflow
Solution 10 - FormsviciouskinidView Answer on Stackoverflow
Solution 11 - FormsBlackCharlyView Answer on Stackoverflow
Solution 12 - FormsEbenezer NikabouView Answer on Stackoverflow
Solution 13 - FormsStrabekView Answer on Stackoverflow