collection-crud/src/Controller/BrandController.php

100 lines
3.0 KiB
PHP
Raw Normal View History

2022-09-29 20:09:31 -04:00
<?php
namespace App\Controller;
use App\Entity\Brand;
use App\Form\BrandType;
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;
#[Route('/brand')]
class BrandController extends AbstractController
{
use FormControllerTrait;
protected const ENTITY = Brand::class;
protected const TEMPLATE_PATH = 'brand/';
protected const ROUTE_PREFIX = 'brand_';
protected const FORM = BrandType::class;
public function __construct(private readonly EntityManagerInterface $entityManager)
{
}
#[Route('/', name: 'brand_index', methods: ['GET'])]
public function index(EntityManagerInterface $entityManager): Response
{
$brands = $entityManager
->getRepository(Brand::class)
->findBy([
], [
'name' => 'asc'
]);
return $this->render('brand/index.html.twig', [
'brands' => $brands,
]);
}
#[Route('/new', name: 'brand_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$brand = new Brand();
$form = $this->createForm(BrandType::class, $brand);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($brand);
$entityManager->flush();
return $this->redirectToRoute('brand_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('brand/new.html.twig', [
'brand' => $brand,
'form' => $form,
]);
}
#[Route('/{id}', name: 'brand_show', methods: ['GET'])]
public function show(Brand $brand): Response
{
return $this->render('brand/show.html.twig', [
'brand' => $brand,
]);
}
#[Route('/{id}/edit', name: 'brand_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, Brand $brand, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(BrandType::class, $brand);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('brand_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('brand/edit.html.twig', [
'brand' => $brand,
'form' => $form,
]);
}
#[Route('/{id}', name: 'brand_delete', methods: ['POST'])]
public function delete(Request $request, Brand $brand, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('delete'.$brand->getId(), $request->request->get('_token'))) {
$entityManager->remove($brand);
$entityManager->flush();
}
return $this->redirectToRoute('brand_index', [], Response::HTTP_SEE_OTHER);
}
}