HegreLand/src/Controller/EmployeeController.php
2024-11-28 15:00:06 +01:00

87 lines
2.8 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\Employee;
use App\Form\EmployeeType;
use App\Repository\EmployeeRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
#[Route('/employee', name: 'employee')]
final class EmployeeController extends AbstractController
{
#[Route('',name: '_index', methods: ['GET'])]
public function index(EmployeeRepository $employeeRepository): Response
{
return $this->render('employee/index.html.twig', [
'employees' => $employeeRepository->findAll(),
]);
}
#[Route('/new', name: '_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$employee = new Employee();
$form = $this->createForm(EmployeeType::class, $employee);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$employee->setPassword(
password_hash($form->get('plainPassword')->getData(), PASSWORD_BCRYPT)
);
$entityManager->persist($employee);
$entityManager->flush();
return $this->redirectToRoute('employee_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('employee/new.html.twig', [
'employee' => $employee,
'form' => $form,
]);
}
#[Route('/{id}', name: '_show', methods: ['GET'])]
public function show(Employee $employee): Response
{
return $this->render('employee/show.html.twig', [
'employee' => $employee,
]);
}
#[Route('/{id}/edit', name: '_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, Employee $employee, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(EmployeeType::class, $employee);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('employee_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('employee/edit.html.twig', [
'employee' => $employee,
'form' => $form,
]);
}
#[Route('/{id}', name: '_delete', methods: ['POST'])]
public function delete(Request $request, Employee $employee, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('delete'.$employee->getId(), $request->getPayload()->getString('_token'))) {
$entityManager->remove($employee);
$entityManager->flush();
}
return $this->redirectToRoute('employee_index', [], Response::HTTP_SEE_OTHER);
}
}