FabRiviere / Livre_Or_Symfony

Développement du projet concernant un livre d'or sur les conférences. Projet du livre Symfony 6.
0 stars 0 forks source link

Uploader des fichiers - images #25

Closed FabRiviere closed 1 year ago

FabRiviere commented 1 year ago
FabRiviere commented 1 year ago

Stockage des paramètres de configuration de manière globale :

Dans le fichier config/services.yaml, ajout des paramètres :

parameters:
    photo_dir: "%kernel.project_dir%/public/uploads/photos"

Implémentation du traitement des fichiers du formulaire dans le contrôleur :

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.

Modification du contrôleur d'administration CommentCrudController.php pour affichage de la photo :

// yield TextField::new('photoFilename')->onlyOnIndex();
    yield ImageField::new('photoFilename')
                    ->setBasePath('/uploads/photos')
                    ->setLabel('Photo')
                    ->onlyOnIndex();