I have an HTML form, which can contain an infinite number of file inputs, declared like so in a twig template:
<form action="my_route">
{% for file in files %}
<label>Current file: {{ file.name }}</label><br>
<label>File to replace (optional): </label>
<input name="{{ file.id }}" type="file"><br>
{% endfor %}
<button type="submit">Send</button>
</form>
The aim of this form is to let user change the files generated by the server, with new files.
My question is, how can i retrieve the sent files, inside my controller ?
I have already tried to retrieve the files from the request
object, like so:
$request->get("the_id");
But, it only gives me the file name as a string, not as a file.
Please note that if rendering the form using Symfony functions (createForm
, renderForm
, ...) make the task easier, I can use them; I've just not yet found a way to use them in this case.
CodePudding user response:
Normally, this is how to retrieve data from a submitted file in Symfony:
if ($form->isSubmitted() && $form->isValid()) {
/**@var UploadedFile $file */
$file = $form->get('file_id')->getData();
if ($file) {
//do your action
}
}
However, since you said there are “infinite” files, you might need something like this:
$file_ids=[/*The array of ids that you retrieve from the DB when making your form*/]
...
if ($form->isSubmitted() && $form->isValid()) {
foreach ($file_ids as $file_id){
/**@var UploadedFile $file */
$file = $form->get($file_id)->getData();
if ($file) {
//do your action
}
}
}