Skip to content
Snippets Groups Projects
Commit fdfb302f authored by AKIFI NAIL's avatar AKIFI NAIL
Browse files

panier

parent b5585cb3
Branches
No related merge requests found
Showing
with 446 additions and 65 deletions
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240320102827 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE produits ADD stock INT NOT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE produits DROP stock');
}
}
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240320102854 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE produits ADD stock INT NOT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE produits DROP stock');
}
}
<?php
namespace App\Controller;
use App\Entity\Panier;
use App\Entity\Produits;
use App\Repository\ProduitsRepository;
use App\Repository\PanierRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
#[Route('/panier')]
class PanierController extends AbstractController
{
#[Route('/', name: 'app_panier_index', methods: ['GET'])]
public function index(PanierRepository $panierRepository): Response
{
return $this->render('panier/index.html.twig', [
'paniers' => $panierRepository->findAll(),
]);
}
#[Route('/new', name: 'app_panier_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$panier = new Panier();
$form = $this->createForm(PanierType::class, $panier);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($panier);
$entityManager->flush();
return $this->redirectToRoute('app_panier_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('panier/new.html.twig', [
'panier' => $panier,
'form' => $form,
]);
}
#[Route('/{id}', name: 'app_panier_show', methods: ['GET'])]
public function show(Panier $panier): Response
{
return $this->render('panier/show.html.twig', [
'panier' => $panier,
]);
}
#[Route('/{id}/edit', name: 'app_panier_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, Panier $panier, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(PanierType::class, $panier);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->flush();
return $this->redirectToRoute('app_panier_index', [], Response::HTTP_SEE_OTHER);
}
return $this->render('panier/edit.html.twig', [
'panier' => $panier,
'form' => $form,
]);
}
#[Route('/{id}', name: 'app_panier_delete', methods: ['POST'])]
public function delete(Request $request, Panier $panier, EntityManagerInterface $entityManager): Response
{
if ($this->isCsrfTokenValid('delete'.$panier->getId(), $request->request->get('_token'))) {
$entityManager->remove($panier);
$entityManager->flush();
}
return $this->redirectToRoute('app_panier_index', [], Response::HTTP_SEE_OTHER);
}
#[Route('/add-to-cart/{produitId}', name: 'app_panier_add_to_cart', methods: ['GET'])]
public function addToCart(int $produitId, ProduitsRepository $produitsRepository, EntityManagerInterface $entityManager, PanierRepository $panierRepository): Response
{
// Obtenez l'utilisateur connecté (cela devrait renvoyer l'instance User actuellement connectée)
$user = $this->getUser();
// Vérifiez que nous avons bien un utilisateur (au cas où cette méthode serait appelée sans utilisateur authentifié)
if (!$user) {
throw $this->createAccessDeniedException('Vous devez être connecté pour ajouter un produit au panier.');
}
// Récupérez le produit en utilisant le ProduitsRepository
$produit = $produitsRepository->find($produitId);
if (!$produit) {
throw $this->createNotFoundException('Le produit n\'existe pas.');
}
// Utilisez la relation OneToOne pour voir si l'utilisateur a déjà un panier
$panier = $user->getPanier();
if (!$panier) {
$panier = new Panier();
$user->setPanier($panier);
$panier->setDateCreation((new \DateTime())->format('Y-m-d H:i:s'));
// Pas besoin de définir `client_id` ici, car il est défini par `setPanier` sur l'entité User
}
// Ajoutez le produit au panier
$panier->addProduitId($produit);
// Sauvegardez le panier dans la base de données
$entityManager->persist($panier);
$entityManager->flush();
// Ajoutez un message flash pour informer l'utilisateur de la réussite de l'ajout
$this->addFlash('success', 'Le produit a été ajouté à votre panier.');
// Redirigez l'utilisateur vers la page du panier ou vers la page du produit
return $this->redirectToRoute('app_panier_show', ['id' => $panier->getId()]);
}
}
<?php
namespace App\Entity;
use App\Repository\PanierRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: PanierRepository::class)]
class Panier
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $date_creation = null;
#[ORM\OneToOne(inversedBy: 'panier', cascade: ['persist', 'remove'])]
private ?User $client_id = null;
#[ORM\ManyToMany(targetEntity: Produits::class, inversedBy: 'paniers')]
private Collection $produit_id;
public function __construct()
{
$this->produit_id = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getDateCreation(): ?string
{
return $this->date_creation;
}
public function setDateCreation(?string $date_creation): static
{
$this->date_creation = $date_creation;
return $this;
}
public function getClientId(): ?User
{
return $this->client_id;
}
public function setClientId(?User $client_id): static
{
$this->client_id = $client_id;
return $this;
}
/**
* @return Collection<int, Produits>
*/
public function getProduitId(): Collection
{
return $this->produit_id;
}
public function addProduitId(Produits $produitId): static
{
if (!$this->produit_id->contains($produitId)) {
$this->produit_id->add($produitId);
}
return $this;
}
public function removeProduitId(Produits $produitId): static
{
$this->produit_id->removeElement($produitId);
return $this;
}
}
......@@ -42,9 +42,13 @@ class Produits
#[ORM\Column]
private ?int $stock = null;
#[ORM\ManyToMany(targetEntity: Panier::class, mappedBy: 'produit_id')]
private Collection $paniers;
public function __construct()
{
$this->sexe = new ArrayCollection();
$this->paniers = new ArrayCollection();
}
public function getId(): ?int
......@@ -161,4 +165,31 @@ class Produits
return $this;
}
/**
* @return Collection<int, Panier>
*/
public function getPaniers(): Collection
{
return $this->paniers;
}
public function addPanier(Panier $panier): static
{
if (!$this->paniers->contains($panier)) {
$this->paniers->add($panier);
$panier->addProduitId($this);
}
return $this;
}
public function removePanier(Panier $panier): static
{
if ($this->paniers->removeElement($panier)) {
$panier->removeProduitId($this);
}
return $this;
}
}
......@@ -31,6 +31,9 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Column]
private ?string $password = null;
#[ORM\OneToOne(mappedBy: 'client_id', cascade: ['persist', 'remove'])]
private ?Panier $panier = null;
public function getId(): ?int
{
return $this->id;
......@@ -106,4 +109,26 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getPanier(): ?Panier
{
return $this->panier;
}
public function setPanier(?Panier $panier): static
{
// unset the owning side of the relation if necessary
if ($panier === null && $this->panier !== null) {
$this->panier->setClientId(null);
}
// set the owning side of the relation if necessary
if ($panier !== null && $panier->getClientId() !== $this) {
$panier->setClientId($this);
}
$this->panier = $panier;
return $this;
}
}
<?php
namespace App\Form;
use App\Entity\Panier;
use App\Entity\Produits;
use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PanierType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('date_creation')
->add('client_id', EntityType::class, [
'class' => User::class,
'choice_label' => 'id',
])
->add('produit_id', EntityType::class, [
'class' => Produits::class,
'choice_label' => 'id',
'multiple' => true,
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Panier::class,
]);
}
}
<?php
namespace App\Repository;
use App\Entity\Panier;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Panier>
*
* @method Panier|null find($id, $lockMode = null, $lockVersion = null)
* @method Panier|null findOneBy(array $criteria, array $orderBy = null)
* @method Panier[] findAll()
* @method Panier[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class PanierRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Panier::class);
}
// /**
// * @return Panier[] Returns an array of Panier objects
// */
// public function findByExampleField($value): array
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->orderBy('p.id', 'ASC')
// ->setMaxResults(10)
// ->getQuery()
// ->getResult()
// ;
// }
// public function findOneBySomeField($value): ?Panier
// {
// return $this->createQueryBuilder('p')
// ->andWhere('p.exampleField = :val')
// ->setParameter('val', $value)
// ->getQuery()
// ->getOneOrNullResult()
// ;
// }
}
......@@ -32,9 +32,12 @@
<a href="/produits" >Boutique</a>
<a href="https://in.linkedin.com/in/jonesvinothjoseph" >Contact</a>
{% if app.user %}
<a href="{{ path('app_user_show', {'id': app.user.id}) }}" ><i class="bi bi-person"></i></a>
<a href="{{ path('app_user_show', {'id': app.user.id}) }}" ><i class="bi bi-basket3"></i></a>
<a href="{{ path('app_user_show', {'id': app.user.id}) }}" ><i class="bi bi-person"></i></a>
{% if app.user.panier %}
<a href="{{ path('app_panier_show', {'id': app.user.panier.id}) }}" ><i class="bi bi-basket3"></i></a>
{% else %}
<a href="" ><i class="bi bi-basket3"></i></a>
{% endif %}
{% else %}
<a href="{{ path('app_user_new') }}" >Crée un compte</a>
{% endif %}
......
<form method="post" action="{{ path('app_panier_delete', {'id': panier.id}) }}" onsubmit="return confirm('Are you sure you want to delete this item?');">
<input type="hidden" name="_token" value="{{ csrf_token('delete' ~ panier.id) }}">
<button class="btn">Delete</button>
</form>
{{ form_start(form) }}
{{ form_widget(form) }}
<button class="btn">{{ button_label|default('Save') }}</button>
{{ form_end(form) }}
{% extends 'base.html.twig' %}
{% block title %}Edit Panier{% endblock %}
{% block body %}
<h1>Edit Panier</h1>
{{ include('panier/_form.html.twig', {'button_label': 'Update'}) }}
<a href="{{ path('app_panier_index') }}">back to list</a>
{{ include('panier/_delete_form.html.twig') }}
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}Panier index{% endblock %}
{% block body %}
<h1>Panier index</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Date_creation</th>
<th>actions</th>
</tr>
</thead>
<tbody>
{% for panier in paniers %}
<tr>
<td>{{ panier.id }}</td>
<td>{{ panier.dateCreation }}</td>
<td>
<a href="{{ path('app_panier_show', {'id': panier.id}) }}">show</a>
<a href="{{ path('app_panier_edit', {'id': panier.id}) }}">edit</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="3">no records found</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{{ path('app_panier_new') }}">Create new</a>
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}New Panier{% endblock %}
{% block body %}
<h1>Create new Panier</h1>
{{ include('panier/_form.html.twig') }}
<a href="{{ path('app_panier_index') }}">back to list</a>
{% endblock %}
{% extends 'base.html.twig' %}
{% block title %}Détails du Panier{% endblock %}
{% block body %}
<h1>Détails du Panier</h1>
{% if panier.produitId %}
<ul>
{% for produit in panier.produitId %}
<li>{{ produit.nom }} - {{ produit.prix }}</li>
{% endfor %}
</ul>
{% else %}
<p>Le panier est vide.</p>
{% endif %}
<a href="{{ path('app_panier_index') }}">Retour à la liste</a>
{% endblock %}
\ No newline at end of file
......@@ -32,6 +32,8 @@
</tbody>
</table>
<a href="{{ path('app_panier_add_to_cart', {'produitId': produit.id}) }}">Ajouter au panierrrr</a>
<a href="{{ path('app_produits_index') }}">back to list</a>
<a href="{{ path('app_produits_edit', {'id': produit.id}) }}">edit</a>
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment