From faee4ca8abf6150efbc14860cde34f109d7c6457 Mon Sep 17 00:00:00 2001 From: thisfro Date: Fri, 30 Apr 2021 19:22:50 +0200 Subject: [PATCH] Implement image upload --- config/services.yaml | 2 ++ src/Controller/AppController.php | 22 +++++++++++++++++++++- templates/app/new_listing.html.twig | 6 ++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/config/services.yaml b/config/services.yaml index c7296dd..c346b29 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -10,6 +10,8 @@ services: _defaults: autowire: true # Automatically injects dependencies in your services. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc. + bind: + $photoDir: "%kernel.project_dir%/public/uploads/photos" # makes classes in src/ available to be used as services # this creates a service per class whose id is the fully-qualified class name diff --git a/src/Controller/AppController.php b/src/Controller/AppController.php index 30cf2ac..a3101d6 100644 --- a/src/Controller/AppController.php +++ b/src/Controller/AppController.php @@ -39,7 +39,7 @@ class AppController extends AbstractController } #[Route('/new', name: 'new_listing')] - public function new_listing(Request $request): Response + public function new_listing(Request $request, string $photoDir): Response { $offering = new Offering(); $form = $this->createForm(OfferingFormType::class, $offering); @@ -51,6 +51,18 @@ class AppController extends AbstractController $offering->setByUser($user); $offering->setCreatedAt(new \DateTime()); + if ($photo = $form['photo']->getData()) { + $filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension(); + try { + $photo->move($photoDir, $filename); + } catch (FileException $e) { + // unable to upload the photo, give up + $this->addFlash("error", "There was an error uploading the photo: ".$e); + return $this->redirectToRoute('new_listing'); + } + $offering->setPhotoFilename($filename); + } + $this->entityManager->persist($offering); $this->entityManager->flush(); @@ -63,4 +75,12 @@ class AppController extends AbstractController 'offering_form' => $form->createView(), ]); } + + #[Route('/offer/{id}', name: 'show_offer')] + public function offer(): Response + { + return $this->render('app/offer.html.twig', [ + 'offer' => $this->getOffering(), + ]); + } } diff --git a/templates/app/new_listing.html.twig b/templates/app/new_listing.html.twig index 8d3e70e..cfd6899 100644 --- a/templates/app/new_listing.html.twig +++ b/templates/app/new_listing.html.twig @@ -1,6 +1,12 @@ {% extends 'base.html.twig' %} {% block body %} + {% for message in app.flashes('error') %} + + {% endfor %} +

Add new offering

{{ form(offering_form) }} {% endblock %} \ No newline at end of file