JeanneD4RK
JeanneD4RK

Reputation: 333

Symfony 4 : $form->getData() returns empty array where same array is filled in $request->request->all()

I'm facing a weird issue right now

Here is my code :

$data = [];

$form = $this->createFormBuilder($data, ["allow_extra_fields" => true,])
    ->add("attributes", FormType::class, ["allow_extra_fields" => true,])
    ->add('save', SubmitType::class, ['label' => 'Save'])
    ->getForm();


$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    return new Response("<pre>".print_r($request->request->all(),1).print_r($data,1)."</pre>");
}

As you can see, for debug purposes, I'm displaying the whole $request->request and $form->getData().

Surprisingly, the first one is totally filled with correct information, the second one is empty.

I'm a bit lazy to censor the information in this array (company information) by hand so here is a censored screenshot of the result :

Controller response

Any idea why the form is not parsed ?

Thanks !

Upvotes: 1

Views: 1812

Answers (2)

ilhan
ilhan

Reputation: 8995

I am using Symfony 6.4 and I had similar issue.

$myObject = $form->getData();
return new Response(json_encode(["aaa" => $myObject]));

returns empty object like {"aaa":{}}

However

$myObject = $form->getData();
$variable = $myObject->getMyProperty();
return new Response(json_encode(["aaa" => $variable]));

returns a value that I have submitted. So, I guess it doesn't have a serializer (that converts it into a string) and we think that it is empty while in fact there is an object. I believe if you or I used a debugger in an IDE we would see that the object was there.

Upvotes: 0

Jakumi
Jakumi

Reputation: 8374

the standard symfony Form class stores extra data in one place, the extraData property, which can be accessed via getExtraData(). This is obviously not particularly helpful in the case of sub forms (it would probably have to be called on the sub form then). I assume, the allow_extra_fields flag is primarily meant to prevent the form from erroring out in case of extra data, since nobody in their right mind would use the Form class for no fields (hence no validation, and none of the perks of using the form class in the first place). So your usage is ... "innovative".

The proper way to do it, would be to very well define the structure which attributes can have within your form (optionally with required set to false), solving most of the actual problems people try to solve with forms. - This is what forms are meant to be, an object that recursively handles the fields/sub forms. If you just want to ignore / circumvent that ... well

The improper way would be, to probably teach some form type - via some datamapper or datatransformer or event handling stuff - to handle any arbitrary data provided.

The easiest way to do it: just use $request->request->all() possibly a deserializer.

Upvotes: 1

Related Questions