0

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.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
qdesmettre
  • 123
  • 6
  • Does this answer your question? [What does enctype='multipart/form-data' mean?](https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean) – DarkBee Jul 21 '22 at 13:56

1 Answers1

0

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
         }
    }
} 
Omar Trkzi
  • 130
  • 1
  • 2
  • 13
  • I assumed there is a `$file_ids` array because you used `{% for file in files %}` in your code, so even if you don't have it, you can always make it out of the variable `files` that you send to the Twig file. If you still have questions, let me know. – Omar Trkzi Jul 21 '22 at 14:29