IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

Custom Method dans Repository


Sujet :

Symfony PHP

  1. #1
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2019
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Avril 2019
    Messages : 20
    Par défaut Custom Method dans Repository
    Bonjour à tous,

    Comme vous vous en doutez, petit souci avec Symfony 4.3

    Je suis un débutant avec ce framework (mais pas en dev! )et mon but est de faire une API pour une appli que je développe avec Angular en front.

    Pour apprendre correctement, je suis sur la doc de Symfony sur le site officiel.

    J'essaie tant bien que mal de faire une méthode custom dans un repository mais j'ai ça comme message d'erreur :

    Undefined method 'findAllGreaterThan'. The method name must start with either findBy, findOneBy or countBy!
    J'ai bien entendu essayer de régénérer mon entity, vider les cache etc... Et bien entendu, chercher sur google et stackOverflow, sans résultat...

    Voici ma classe :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    <?php
     
    namespace App\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\Validator\Constraints as Assert;
     
    /**
     * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
     */
    class Product
    {
        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;
     
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\NotBlank
         */
        private $name;
     
        /**
         * @ORM\Column(type="integer")
         * @Assert\NotBlank
         */
        private $price;
     
        /**
         * @ORM\Column(type="text")
         * @Assert\NotBlank
         */
        private $description;
     
        public function getId(): ?int
        {
            return $this->id;
        }
     
        public function getName(): ?string
        {
            return $this->name;
        }
     
        public function setName(string $name): self
        {
            $this->name = $name;
     
            return $this;
        }
     
        public function getPrice(): ?int
        {
            return $this->price;
        }
     
        public function setPrice(int $price): self
        {
            $this->price = $price;
     
            return $this;
        }
     
        public function getDescription(): ?string
        {
            return $this->description;
        }
     
        public function setDescription(string $description): self
        {
            $this->description = $description;
     
            return $this;
        }
    }
    Voici mon repository :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    <?php
     
    namespace App\Repository;
     
    use App\Entity\Product;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Doctrine\Common\Persistence\ManagerRegistry;
    use Doctrine\ORM\EntityManagerInterface;
    use Doctrine\ORM\EntityRepository;
     
    /**
     * @method Product|null find($id, $lockMode = null, $lockVersion = null)
     * @method Product|null findOneBy(array $criteria, array $orderBy = null)
     * @method Product[]    findAll()
     * @method Product[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
     */
    class ProductRepository extends ServiceEntityRepository
    {
        public function __construct(ManagerRegistry $registry)
        {
            parent::__construct($registry, Product::class);
        }
     
        /**
         * @return Product[]
         */
        public function findAllGreaterThanPrice($price): array
        {
            $entityManager = $this->getEntityManager();
     
            $query = $entityManager->createQuery(
                'SELECT p
                FROM App\Entity\Product p
                WHERE p.price > :price
                ORDER BY p.price ASC'
            )->setParameter('price', $price);
     
            return $query->getResult();
        }
     
        // /**
        //  * @return Product[] Returns an array of Product objects
        //  */
        /*
        public function findByExampleField($value)
        {
            return $this->createQueryBuilder('p')
                ->andWhere('p.exampleField = :val')
                ->setParameter('val', $value)
                ->orderBy('p.id', 'ASC')
                ->setMaxResults(10)
                ->getQuery()
                ->getResult()
            ;
        }
        */
     
        /*
        public function findOneBySomeField($value): ?Product
        {
            return $this->createQueryBuilder('p')
                ->andWhere('p.exampleField = :val')
                ->setParameter('val', $value)
                ->getQuery()
                ->getOneOrNullResult()
            ;
        }
        */
    }
    et voici mon controller :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    <?php
     
    namespace App\Controller;
     
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\Routing\Annotation\Route;
     
    use App\Entity\Product;
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Component\HttpFoundation\Response;
    // use Symfony\Component\Validator\ValidatorInterface;
     
    class ProductController extends AbstractController
    {
        /**
         * @Route("/product", name="create_product")
         */
        public function createProduct():Response
        {
           $entityManager = $this->getDoctrine()->getManager();
     
           $product = new Product();
           $product->setName('Iphone');
           $product->setPrice(899);
           $product->setDescription('Amazing Iphone');
     
        //    $errors = $validator->validate($product);
        //    if (count($errors) > 0){
        //        return new Response((string)$errors, 400);
        //    }
     
           $entityManager->persist($product);
     
           $entityManager->flush();
     
           return new Response('Produit sauvé avec un id ' . $product->getId());
        }
     
        /**
         * @Route("/product/{id}", name="product_show")
         */
        public function show($id)
        {
     
            $product = $this->getDoctrine()
                ->getRepository(Product::class)
                ->find($id);
     
            if (!$product) {
                throw $this->createNotFoundException(
                    'Pas de produit avec un id ' . $id
                );
            }
     
            return new Response('Regarde ce super produit ' .$product->getName());
        }
        /**
         * @Route("/product/list/{minPrice}", name="product_list")
         */
        public function showProductList($minPrice)
        {
     
            $product = $this->getDoctrine()
                ->getRepository(Product::class)
                ->findAllGreaterThan($minPrice);
     
            return new Response($product);
        }
     
        /**
         * @Route("/product/edit/{id}")
         */
        public function editProduct($id)
        {
            $entityManager = $this->getDoctrine()->getManager();
            $product = $entityManager->getRepository(Product::class)->find($id);
     
            if (!$product) {
                throw $this->createNotFoundException(
                    'Pas de produit avec un id ' . $id
                );
            }
     
            $product->setName('Keyboard');
            $entityManager->flush();
     
            return $this->redirectToRoute('product_show', [
                'id' => $product->getId()
            ]);
        }
     
        /**
         * @Route("/product/delete/{id}")
         */
        public function deleteProduct($id)
        {
            $entityManager = $this->getDoctrine()->getManager();
            $product = $entityManager->getRepository(Product::class)->find($id);
     
            if (!$product) {
                throw $this->createNotFoundException(
                    'Pas de produit avec un id ' . $id
                );
            }
     
            $entityManager->remove($product);
            $entityManager->flush();
     
            return new Response('Le produit à bien été supprimé !');
        }
    }
    Je n'arrive pas à voir d'ou ça peut venir mais j'avoue, j'ai un peu le nez dans le guidon...

    Si quelqu'un à une idée, ce serait vachement sympa....

    Merci à vous

  2. #2
    Membre Expert
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Août 2012
    Messages
    631
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Août 2012
    Messages : 631
    Par défaut
    Citation Envoyé par Black-k-fee Voir le message


    Undefined method 'findAllGreaterThan'. The method name must start with either findBy, findOneBy or countBy!
    bonjour,
    tu n’appelles pas la bonne méthode car findAllGreaterThan n'existe pas dans ProductRepository.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    /**
         * @Route("/product/list/{minPrice}", name="product_list")
         */
        public function showProductList($minPrice)
        {
     
            $product = $this->getDoctrine()
                ->getRepository(Product::class)
                ->findAllGreaterThanPrice($minPrice); // c'est bien findAllGreaterThanPrice et non findAllGreaterThan
     
            return new Response($product);
        }

  3. #3
    Membre averti
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2019
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Avril 2019
    Messages : 20
    Par défaut
    Pfff....

    Quel naze je fais !!

    J'avais prévenu que j'avais la tête dans le guidon...

    Merci encore et vraiment désolé pour cette erreur à la c...

Discussions similaires

  1. Appel d'un methode dans un bouton
    Par ToTo94 dans le forum AWT/Swing
    Réponses: 5
    Dernier message: 01/03/2006, 20h03
  2. [VS2005][VB.Net] Custom Format dans un DataGridView
    Par Vonotar dans le forum VB.NET
    Réponses: 10
    Dernier message: 22/11/2005, 08h15
  3. [débutant] appeler plusieurs methodes dans une page html
    Par soulhouf dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 24/08/2005, 19h20
  4. [Language]utilisation de méthodes dans différentes classes
    Par The Wretched dans le forum Langage
    Réponses: 4
    Dernier message: 09/05/2005, 16h17
  5. Visibilité de methodes dans Classe de Class
    Par Math75 dans le forum C++
    Réponses: 9
    Dernier message: 28/09/2004, 12h48

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo