So, what I need is a basic file upload. What I have is Symfony 4 and VichUploaderBundle, integrated exactly as described https://symfony.com/doc/current/bundles/EasyAdminBundle/integration/vichuploaderbundle.html
Entity is marked as @Vich\Uploadable, fields are defined correcty:
/**
* @Vich\UploadableField(mapping="images", fileNameProperty="fileName")
* @var File
*/
private $file;
/**
* @ORM\Column(type="string", length=255)
*/
private $fileName;
This is my Type:
class MyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('file', VichImageType::class, ['allow_file_upload' => true])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => My::class,
'allow_extra_fields' => false,
'http_method' => 'POST'
]);
$resolver->setRequired('http_method');
}
}
What I have in my controller:
$form = $this->createForm(MyType::class, null);
$form->submit(array_merge($request->request->all(), $request->files->all()));
if ($form->isSubmitted() && $form->isValid()) {
/** @var $my */
$my = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($my);
$em->flush();
return $this->json($my);
}
The outcome of this is a TransformationException:
Compound forms expect an array or NULL on submission.
I've debugged the whole thing with xDebug - it successfully submits name
field, and even file
field, for the first time. But then, for some reason, it thinks it's a compound form and tries to submit it one more time - which obviously leads to a transformation exception https://github.com/symfony/form/blob/master/Form.php#L571
And, when I try to set 'compound' => false
, it doesn't submit the file field at all.
What might be the problem here? I've seen in the docs, that for using it with EasyAdmin it's enough to just specify the field name and type 'vich_image', why it doesn't work outside the EasyAdmin? You could notice, by the way, that I've added extra parameter 'allow_file_upload' => true
as it wasn't submitting without it https://github.com/symfony/form/blob/master/Form.php#L534
So, a bit of further research has lead me to this answer https://github.com/dustin10/VichUploaderBundle/issues/769#issuecomment-477173161
And the solution is to submit the form like this:
$form->submit(array_merge(
$request->request->all(),
['file' => $request->files->all()]
));