I am using the method explained here to implement multiple file upload, but it can't find a way to make it work. I know there is already a lot of questions about it, but I couldn't find a suitable answer for my case.
Note that I am storing file's content in the database, thanks to a file Entity with Name, Content and Type attributes. However in order to make it work, I am not mapping the form to this entity.
So, my controller looks like this :
$files = [];
$form = $this->createForm(MultipleFilesType::class, []);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$files = $form->getData();
dump($files);
foreach ($files as $file)
{
//code that stores the file in the database which works fine and is not relevant to my problems I think
}
return // redirect to some page
}
return //form to the view
My MultipleFilesType is the collection which embed multiple addFileType :
class MultipleFilesType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('files', CollectionType::class, array (
'entry_type' => addFileType::class,
'allow_add' => true,
'allow_delete' => true,
'label' => false,
'mapped' => false,
'data' => array(
array ('file' => null)
)
))
;
}
}
and my addFileType is this :
class AddFileType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class, array (
'label' => false
))
;
}
}
In my view I can add / remove fields thanks to some JQuery explained in the linked documentation. (The code is more or less the same as the one in the doc, except that I am not working with Entites, so I am not showing it here).
I first tried to do single file uploads, which worked nicely, and then I tried the above code, using the collectionType and a $files array to retrieve the data from the form to the controller, but I am having these issues :
When I submit the form, apparently the values of files after the first one are not valid.
When I submit only one file (no validation error), the dump($files) in the controller show me an empty array no matter what.
Any help would be appreciated =) Don't hesitate to ask for more code if you think it is needed.
Thank you !
Instead of
$files = $form->getData();
it was
$files = $form->get("files")->getData();