On my symfony project I have an ajax call to upload multiple files.Currently accessing it by
$files = $request->files->get('file');
But for further coding used foreach on $files variable but not working.
On another page have the same functionality but that is page submit so accessing with $form object that is working fine there.
$form->get('file')->getData();
What is the difference between this parameter accessing method please help.
CodePudding user response:
In short: Because the file
field doesn't exist in the second case.
The more detailed explanation is this:
The Form Component is built on top of HttpFoundation (that provides an object-oriented way to deal with requests and responses) and some other symfony components and provides not only the form builder but validation, csrf protection, object mapping and other goodies.
In the first example you are using the File ParameterBag
provided by HttpFoundation
. It's basically the $_FILES
superglobal, and you are accessing the one named file
in particular. As it's an ajax call, I'd bet is a handcrafted form or a purely js function; the file
field is named just that. In this case you are dealing directly with the raw http request. Bob's your uncle.
When using the form component however, if you have a form field named file
it won't show up in the request as such; the form is sent as an array in the form:
[
'form_name' => [
'field1' => 'value1',
// More fields or nested arrays
],
];
The component does this to allow for multiple forms with the same fields while being able to identify them, etc.
As part of the form handling, the fields in the request are mapped back to the form fields. That's what your app is using in the second case, the Form
object representation of the data sent. For more information about the process, refer to the documentation. You can also inspect the request with your browser tools or the Symfony Profiler to gain more insight.