Reputation: 72
iam developing an multiple File Uploader.
To understand my problem, I try to describe it for you:
I have two Entities (Objects and Images) with an "1 ... n" Relation, so that every Object can have "n" Images.
If I try to upload some Images, my Controller throw some exception, but I dont use Images Entity. Dont know how to fix this Problem and get some working Uploader.
Expected argument of type "App\Entity\Images", "Symfony\Component\HttpFoundation\File\UploadedFile" given.
Controller:
/**
* @Route("/new", name="objects_new", methods="GET|POST")
*/
public function new(Request $request): Response
{
$object = new Objects();
$form = $this->createForm(ObjectsType::class, $object);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$file = $form->get('logo')->getData();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
$file->move(
$this->getParameter('logo_directory'),
$fileName
);
$object->setLogo($fileName);
foreach ($request->files as $uploadedFile) {
$uploadedFile = current($uploadedFile['file']);
dump($uploadedFile);
}
$em->persist($object);
$em->flush();
return $this->redirectToRoute('home');
}
return $this->render('objects/new.html.twig', [
'object' => $object,
'form' => $form->createView(),
]);
}
Objects Entity:
/**
* @ORM\OneToMany(targetEntity="App\Entity\Images", mappedBy="objects")
*/
private $images;
Images Entity:
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Objects", inversedBy="images")
*/
private $objects;
ObjectsType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('designation')
->add('description')
->add('place')
->add('coordL', null, array(
'attr' => array('readonly' => 'true'),
))
->add('coordB', null, array(
'attr' => array('readonly' => 'true'),
))
->add('category')
->add('logo', FileType::class, array('label' => ' ', 'data_class' => null))
->add('images', FileType::class, array('label' => 'Bilder (png, jpg, jpeg)', 'data_class' => null, 'multiple' => true))
;
}
If someone know, how to fix my Problem so help me please.
Upvotes: 1
Views: 417
Reputation: 1507
Your $images
field is set to be of App\Entity\Images
type, but in your FormType, you're setting it to FileType
.
Here is the line i'm talking about :
->add('images', FileType::class, array('label' => 'Bilder (png, jpg, jpeg)', 'data_class' => null, 'multiple' => true))
From this point, you have several ways to solve your problem, among which :
Either add the "mapped => false" option to that field in your FormType, then handle the process (of transforming a file to an Image
entity ) manually from your controller.
Or make a custom ImageFormType
, mapped to your Image
entity, which contains your FileType field ( could require some tricky code though )
See : form type mapped false symfony2 and https://symfony.com/doc/current/form/create_custom_field_type.html for more informations.
Upvotes: 1