This repository has been archived on 2024-10-16. You can view files and clone it, but cannot push or open issues or pull requests.
pflaenz.li-Symfony/src/Controller/UserController.php

83 lines
2.4 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\Wish;
use App\Entity\User;
use App\Form\WishFormType;
use App\Repository\WishRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;
class UserController extends AbstractController
{
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
#[Route('/user', name: 'user_page')]
public function user(): Response
{
return $this->render('user/index.html.twig', [
'user' => $this->getUser(),
]);
}
#[Route('/user/{id}', name: 'public_wishlist')]
public function show_user(User $user, WishRepository $wishRepository): Response
{
return $this->render('user/public_wishlist.html.twig', [
'username' => $user->getUsername(),
'wishes' => $wishRepository->findByUser($user),
]);
}
#[Route('/wishlist', name: 'wishlist')]
public function wishlist(Request $request, WishRepository $wishRepository): Response
{
$wish = new Wish();
$form = $this->createForm(WishFormType::class, $wish);
$user = $this->getUser();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$wish->setByUser($user);
$this->entityManager->persist($wish);
$this->entityManager->flush();
$this->addFlash("success", "Successfully added the new wish!");
return $this->redirectToRoute('wishlist');
}
return $this->render('user/wish.html.twig', [
'user' => $this->getUser(),
'wishes' => $wishRepository->findByUser($user),
'wish_form' => $form->createView(),
]);
}
#[Route('/wish/delete/{id}', name: 'delete_wish')]
public function deleteWish(Wish $wish): Response
{
$user = $this->getUser();
$user->removeWish($wish);
$this->entityManager->persist($wish);
$this->entityManager->flush();
$this->addFlash("success", "Successfully removed the wish!");
return $this->redirectToRoute('wishlist');
}
}