Extract data from form objects as array of values

2019-06-14 16:30发布

问题:

I'm building a web application using Symfony 2.5. I am currently struggling with internally forwarding requests with POST/PUT form data attached. I've had a previous a previous question resolved by Cerad concerning this point. For the full story see:

Subrequests with post vars

But now that I have the solution for forwarding, I can't seem to be able to find a way to extract form data as an array of values that could be attached to the sub request. I tried using Form::getData() but it returned an entity, I also tried to use Form::all() but I get an array of Form objects. I could iterate over all these to get the effective values in the form, but I feel like there should be a better solution.

Any idea ?

回答1:

If you performing HTTP redirect you need to save all you form data to the Session before you redirect and than read it from the Session.

UPD: i found chapter in documentation that may help you Using a Form without a Class

This is actually really easy:

they said. If it doesn't help you can try one of conversion methods.

Simple "casting" (objects inside parent object will remains as objects):

$array = (array) $object;

or using get_object_vars()

$array = get_object_vars($object);

or using ArrayObject:

$arrayObject = new ArrayObject($object);
$array = $arrayObject->getArrayCopy();

and finally JSON encode/decode

$array = json_decode(json_encode($object), true);