简体   繁体   中英

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 :

控制器响应

Any idea why the form is not parsed ?

Thanks !

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM