Implement image upload

This commit is contained in:
Jannis Portmann 2021-04-30 19:22:50 +02:00
parent 14d242f173
commit faee4ca8ab
3 changed files with 29 additions and 1 deletions

View file

@ -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

View file

@ -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(),
]);
}
}

View file

@ -1,6 +1,12 @@
{% extends 'base.html.twig' %}
{% block body %}
{% for message in app.flashes('error') %}
<div class="alert alert-error" role="alert">
{{ message }}
</div>
{% endfor %}
<h1 class="mb-3">Add new offering</h1>
{{ form(offering_form) }}
{% endblock %}