Partage
  • Partager sur Facebook
  • Partager sur Twitter

Ajout/Suppression d'item

Sujet résolu
    22 mai 2020 à 17:06:57

    Bonjour, 

    Je viens vers vous car j'arrive pas à ajouter et supprimer des items. 

    Ça doit être tout con et je sens que c'est parce que j'appelle pas les méthodes du controller mais je vois pas comment faire. 

    Voici mes fichiers : 

    Le controller (Avec les methodes create et delete) : 

    <?php
    
    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\Routing\Annotation\Route;
    
    class IngredientController extends AbstractController
    {
        /**
         * @Route("/ingredient", name="ingredient")
         */
        public function index()
        {
            return $this->render('ingredient/index.html.twig', [
                'controller_name' => 'IngredientController',
            ]);
        }
    
        /**
         * Create ingredient
         * 
         * @Route("/ingredient/create/{name}/{price}", name="create_ingredient")
         *
        */
        public function createIngredient(): Response
        {
            // you can fetch the EntityManager via $this->getDoctrine()
            // or you can add an argument to the action: createIngredient(EntityManagerInterface $entityManager)
            $entityManager = $this->getDoctrine()->getManager();
    
            $ingredient = new Ingredient();
    
            $ingredient->setName('Keyboard');
            $ingredient->setPrice(1999);
    
            // tell Doctrine you want to (eventually) save the Ingredient (no queries yet)
            $entityManager->persist($ingredient);
    
            // actually executes the queries (i.e. the INSERT query)
            $entityManager->flush();
    
            return new Response('Ingrédient avec l\'id '.$ingredient->getId().' à été ajouté');
        }
    
        /**
         * Delete ingredient
         * 
         * @Route("/ingredient/delete/{id}", name="delete_ingredient")
         *
        */
        public function deleteIngredient(): Response
        {
            // you can fetch the EntityManager via $this->getDoctrine()
            // or you can add an argument to the action: createIngredient(EntityManagerInterface $entityManager)
            $entityManager = $this->getDoctrine()->getManager();
    
            $ingredient = $ingredientRepo->findOneBy(['id' => $id]);
    
            $entityManager->remove($product);
            $entityManager->flush();
    
            return new Response('Ingrédient avec l\'id '.$ingredient->getId().' à été supprimé');
        }
    }
    

    Ici tout me parait bon, juste je ne sais pas si le "FindOneBy" est bon pour supprimer un ingrédient par rapport à son id. Et que j'aimerais que, lors de l'ajout, ça soit les valeurs que j'ai rentré et non des valeurs en dur :)  

    Mon repository (Qui est inchangé depuis sa création) : 

    <?php
    
    namespace App\Repository;
    
    use App\Entity\Ingredients;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Doctrine\Persistence\ManagerRegistry;
    
    /**
     * @method Ingredients|null find($id, $lockMode = null, $lockVersion = null)
     * @method Ingredients|null findOneBy(array $criteria, array $orderBy = null)
     * @method Ingredients[]    findAll()
     * @method Ingredients[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
     */
    class IngredientsRepository extends ServiceEntityRepository
    {
        public function __construct(ManagerRegistry $registry)
        {
            parent::__construct($registry, Ingredients::class);
        }
    
        // /**
        //  * @return Ingredients[] Returns an array of Ingredients objects
        //  */
        /*
        public function findByExampleField($value)
        {
            return $this->createQueryBuilder('i')
                ->andWhere('i.exampleField = :val')
                ->setParameter('val', $value)
                ->orderBy('i.id', 'ASC')
                ->setMaxResults(10)
                ->getQuery()
                ->getResult()
            ;
        }
        */
    
        /*
        public function findOneBySomeField($value): ?Ingredients
        {
            return $this->createQueryBuilder('i')
                ->andWhere('i.exampleField = :val')
                ->setParameter('val', $value)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }
        */
    }
    

    Et mon Twig : 

    {% extends 'base.html.twig' %}
    
    {% block title %}Ingredient{% endblock %}
    
    {% block body %}
    <style>
        .example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
        .example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
    </style>
    
    <div class="example-wrapper">
        <h1>MES INGREDIENTS</h1>
    
        {# {% if ingredient.count < 0 %} #}
            <p>Vous n'avez actuellement aucun ingrédients commencez par en ajouter un : </p>
            
            <div class="contenu-ajout-ingredient">
                <label>Name : </label><input type="text" class="input-name" placeholder="Nom de l'ingrédient"><br>
                <label>Price : </label><input type="text" class="input-price" placeholder="Prix de l'ingrédient">
                <input type="submit" class="ajout-ingredient-button" value="AJOUTER">
            </div>
        {# {% else %} #}
    
        {# AFFICHER LA LISTE DES INGREDIENTS DE L'UTILISATEUR CONNECTE #}
    
        {# POUVOIR AJOUTER ET SUPPRIMER DES PRODUITS #}
    
        {# {% end if %} #}
    </div>
    {% endblock %}
    

    Là c'est surement mon form (Qui n'en est pas un au final) qui peut poser problème. 

    (Pour la suppression c'est pas encore fait mais ça sera via un bouton comme l'ajout).

    Est ce qu'il faut que je fasse un form avec un "ACTION = /ingredient/create/{name}/{price}" ? 


    Voilà j'ai pas beaucoup de piste pour résoudre le problème et même après avoir vu un tuto ça m'a pas du tout aidé. 

    Si vous avez des pistes je suis preneur 

    Merci 

    • Partager sur Facebook
    • Partager sur Twitter
      23 mai 2020 à 7:21:16

      Bonjour,

      Je crois qu'il te faut suivre à nouveau les tutos ... car les questions que tu poses sont en fait en partie les bases de l'usage de Symfony.

      Pour ta suppression, il n'y a pas un problème en allant chercher en ligne 58 un objet ingredient et en voulant supprimer en ligne 60 un product ?

      Si tu recherches par l'id alors la méthode find suffit : pourquoi un findOneBy ????

      Revois les cours car ce forum n'est pas destiné à faire de la formation.

      A+

      • Partager sur Facebook
      • Partager sur Twitter

      Ajout/Suppression d'item

      × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
      × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
      • Editeur
      • Markdown