84

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}
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
VishwaKumar
  • 3,433
  • 8
  • 44
  • 72

13 Answers13

100

Simply :

$data = $form->getData();
Hubert Perron
  • 3,022
  • 5
  • 34
  • 28
  • 2
    Nice Answer - RE: below answers. Symfony often allows for many ways to get similar results. It's always good to research "Best Practices" when looking for SF solutions. – JustinP Dec 12 '12 at 16:14
  • 11
    For new versions: $data = $form->all(); – Gmajoulet Aug 11 '14 at 14:13
98

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

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

I hope it helps.

pkout
  • 6,430
  • 2
  • 45
  • 55
  • 2
    Hmmm strange, i got it working with $request->request->get('username'); Did you pass the request object as a parameter to the action? And you need to include the Request Class too in the above. – VishwaKumar Apr 06 '12 at 05:53
61

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.

Richard Turner
  • 12,506
  • 6
  • 36
  • 37
albert
  • 1,766
  • 1
  • 21
  • 24
21

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

Alessandro Lai
  • 2,254
  • 2
  • 24
  • 32
19

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();
Saman Mohamadi
  • 4,454
  • 4
  • 38
  • 58
8

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

PJately
  • 477
  • 7
  • 7
6

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();
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
4

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.
Leward
  • 125
  • 5
Chicna
  • 180
  • 1
  • 7
  • This is what I was looking for. The project I'm working on is in symfony 2.0 and can't be updated. – Naomi Jun 02 '15 at 15:29
4

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.

VishwaKumar
  • 3,433
  • 8
  • 44
  • 72
3
private function getFormDataArray($form)
{
    $data = [];
    foreach ( $form as $key => $value) {
        $data[$key] = $value->getData();
    }
    return $data;
}
  • If your form have subforms, this code should be like: `$data[$key] = is_object($value->getData()) ? $this->getFormDataArray($value) : $value->getData();` – Aliance Dec 15 '16 at 07:51
2

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 ?

BlackCharly
  • 649
  • 4
  • 8
  • Thanks @BlackCharly I am beginning to read the documentation. I have also updated the code to give the reader complete clarity with the same. Appreciate your help. – VishwaKumar Jan 24 '12 at 13:43
1

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

$request->request->get('name');
Ebenezer Nikabou
  • 369
  • 4
  • 14
0

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

Strabek
  • 2,391
  • 3
  • 32
  • 39