Accès à une entité via son identifiant et en utilisant Doctrine\ORM\EntityManagerInterface
use Doctrine\ORM\EntityManagerInterface;
#[Route('/auteur/{id}', name: 'auteurById')]
public function auteurByIdAction(EntityManagerInterface $entityManager, int $id): Response
{
$auteur = $entityManager->getRepository(Auteur::class)->find($id);
if (!$auteur) {
throw $this->createNotFoundException(
'No auteur found for id ' . $id
);
}
return $this->render('auteur/auteur.html.twig', ['auteur' => $auteur]);
}
Possibilité de passer directement par App\Repository\AuteurRepository
use App\Repository\AuteurRepository;
#[Route('/auteur/{id}', name: 'auteurById')]
public function auteurByIdAction(AuteurRepository $auteurRep, int $id): Response
{
$auteur = $auteurRep->find($id);
if (!$auteur) {
throw $this->createNotFoundException(
'No auteur found for id ' . $id
);
}
return $this->render('auteur/auteur.html.twig', ['auteur' => $auteur]);
}
find(int $id); // retourne l'entité correspondant à l'id
findOneBy(array $criteria); // retourne une entité parmi celles respectant le critère
findAll(); // retourne un tableau d'entités
findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null); // retourne un tableau
count(array $criteria = []); // nombre d'entités respectant le critèreCréation d'une entité
#[Route('/newauteur', name: 'newAuteur')]
public function createAuteurAction(EntityManagerInterface $entityManager): Response
{
$auteur = new Auteur();
$auteur->setAutNom('Simmons');
$auteur->setAutPrenom('Dan');
// indique à Doctrine que l'auteur sera sauvegardé
// (mais ce n'est pas encore fait !)
$entityManager->persist($auteur);
// Exécute la requête SQL
$entityManager->flush();
return new Response('Nouvel auteur sauvé avec l\'id ' . $auteur->getId());
}
Modification d'une entité
#[Route('/auteur/update/{id}', name: 'auteur_update')]
public function updateAuteurAction(EntityManagerInterface $entityManager, int $id): Response
{
$auteur = $entityManager->getRepository(Auteur::class)->find($id);
if (!$auteur) {
throw $this->createNotFoundException(
'Pas d\'auteur trouvé pour l\' id '.$id
);
}
$auteur->setNom('Ascully');
$entityManager->flush();
return $this->redirectToRoute('auteurById', [
'id' => $auteur->getId()
]);
}
$entityManager->remove($auteur);
$entityManager->flush();