Closed FabRiviere closed 1 year ago
Dans le fichier config/services.yaml, ajout des paramètres :
parameters:
photo_dir: "%kernel.project_dir%/public/uploads/photos"
use Symfony\Component\DependencyInjection\Attribute\Autowire;
#[Route('/conference/{slug}', name: 'conference')]
public function show(Request $request, Conference $conference, CommentRepository $commentRepository,
-> #[Autowire('%photo_dir%')] string $photoDir): Response
{
$comment = new Comment();
$formComment = $this->createForm(CommentType::class, $comment);
$formComment->handleRequest($request);
if ($formComment->isSubmitted() && $formComment->isValid()) {
$comment->setConference($conference);
-> //! Traitement des photos
-> if ($photo = $formComment['photo']->getData()) {
-> $filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension();
-> $photo->move($photoDir, $filename);
-> $comment->setPhotoFilename($filename);
}
$this->entityManager->persist($comment);
$this->entityManager->flush();
return $this->redirectToRoute('conference', ['slug' => $conference->getSlug()]);
}
$offset = max(0, $request->query->getInt('offset', 0));
$paginator = $commentRepository->getCommentPaginator($conference, $offset);
return $this->render('conference/show.html.twig', [
'conference' => $conference,
'comments' => $paginator,
'previous' => $offset - CommentRepository::PAGINATOR_PER_PAGE,
'next' => min(count($paginator), $offset + CommentRepository::PAGINATOR_PER_PAGE),
'comment_form' => $formComment,
]);
}
Pour gérer les uploads de photos, nous créons un nom aléatoire pour le fichier. Ensuite, nous déplaçons le fichier uploadé à son emplacement final (le répertoire photo). Enfin, nous stockons le nom du fichier dans l'objet Comment.
// yield TextField::new('photoFilename')->onlyOnIndex();
yield ImageField::new('photoFilename')
->setBasePath('/uploads/photos')
->setLabel('Photo')
->onlyOnIndex();