-1

Im working on Symfony 4.2. I get this error

App\Entity\Shopcart object not found by the @ParamConverter annotation.

when I try to delete or edit an item on shopcard.I tried many solution but failed.I need your suggestions.

Here is my ShopcartController

<?php

namespace App\Controller;

use App\Entity\Shopcart;
use App\Form\ShopcartType;
use App\Repository\ProductRepository;
use App\Repository\ShopcartRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/shopcart")
 */
class ShopcartController extends AbstractController
{
    /**
     * @Route("/", name="shopcart_index", methods={"GET"})
     */
    public function index(ShopcartRepository $shopcartRepository, ProductRepository $productRepository): Response
    {
        $slider=$productRepository->findBy([], ['name'=>'ASC'], 3);     //slider doesn't exist hatası için ekledim

        return $this->render('shopcart/index.html.twig', [
            'shopcarts' => $shopcartRepository->getAllShops(),
            'slider' => $slider,    //slider doesn't exist hatası için ekledim

        ]);
    }

    /**
     * @Route("/new", name="shopcart_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $shopcart = new Shopcart();
        $form = $this->createForm(ShopcartType::class, $shopcart);
        $form->handleRequest($request);
        echo $submittedToken=$request->request->get('token');
        if($this->isCsrfTokenValid('add-item', $submittedToken)) {      //alınan tokenla uyuşuyorsa göre sepete ekliyor
            if ($form->isSubmitted()) {
                $entityManager = $this->getDoctrine()->getManager();
                $user=$this->getUser();

                $shopcart->setQuantity($request->request->get('quantity'));
                $shopcart->setUserid($user->getid());

                $entityManager->persist($shopcart);
                $entityManager->flush();

                return $this->redirectToRoute('shopcart_index');
            }
        }
        return $this->render('shopcart/new.html.twig', [
            'shopcart' => $shopcart,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="shopcart_show", methods={"GET"})
     */
    public function show(Shopcart $shopcart): Response
    {
        return $this->render('shopcart/show.html.twig', [
            'shopcart' => $shopcart,
        ]);
    }

    /**
     * @Route("/{id}/edit", name="shopcart_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Shopcart $shopcart): Response
    {
        $form = $this->createForm(ShopcartType::class, $shopcart);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('shopcart_edit',['id'=>$shopcart->getId()]);
        }

        return $this->render('shopcart/edit.html.twig', [
            'shopcart' => $shopcart,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="shopcart_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Shopcart $shopcart): Response
    {

        //methodu post ile değiştirip dene
        if ($this->isCsrfTokenValid('delete'.$shopcart->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($shopcart);
            $entityManager->flush();
        }

        return $this->redirectToRoute('shopcart_index');
    }


    /**
     * @Route("/{id}/del", name="shopcart_del", methods={"DELETE"})
     */
    public function del(Request $request, Shopcart $shopcart): Response
    {
        $em=$this->getDoctrine()->getManager();
        $em->remove($shopcart);
        $em->flush();

        return $this->redirectToRoute('shopcart_index');
    }
}

And here is ShopcartRepository.I use only getAllShops method.

<?php

namespace App\Repository;

use App\Entity\Shopcart;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use phpDocumentor\Reflection\Types\Integer;

/**
 * @method Shopcart|null find($id, $lockMode = null, $lockVersion = null)
 * @method Shopcart|null findOneBy(array $criteria, array $orderBy = null)
 * @method Shopcart[]    findAll()
 * @method Shopcart[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class ShopcartRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Shopcart::class);
    }

    // /**
    //  * @return Shopcart[] Returns an array of Shopcart objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('s')
            ->andWhere('s.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('s.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Shopcart
    {
        return $this->createQueryBuilder('s')
            ->andWhere('s.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */

    //LET JOIN WITH SQL
    public function getAllShops():array
    {
        $conn = $this->getEntityManager()->getConnection();
        $sql = '
    SELECT p.name, p.price, s.*, u.id FROM shopcart s, product p, user u
    WHERE s.productid = p.id and s.userid=u.id
     ';
        $stmt=$conn->prepare($sql);
        $stmt->execute();

        return $stmt->fetchAll();
    }


    public function getUserShopCartTotal($userid): float
    {
        $em=$this->getEntityManager();
        $query= $em->createQuery('
        SELECT sum(p.price *s .quantity) as total
            FROM App\Entity\Shopcart s, App\Entity\Product p
            WHERE  s.productid = p.id and s.userid=:userid
')
            ->setParameter('userid',$userid);
        $result=$query->getResult();

        if($result[0]['total']!=null){
            return $result[0]["total"];
        } else {
            return 0;
        }
    }

    public function getUserShopCartCount($userid): Integer
    {
        $em=$this->getEntityManager();
        $query= $em->createQuery('
        SELECT count(s.id) as shopcount
            FROM App\Entity\Shopcart s
            WHERE s.userid=:userid
')
            ->setParameter('userid',$userid);
        $result=$query->getResult();

        if($result[0]['shopcount']!=null){
            return $result[0]["shopcount"];
        } else {
            return 0;
        }
    }

    public function getUserShopCart($userid): array
    {
        $em=$this->getEntityManager();
        $query= $em->createQuery('
        SELECT p.name, p.price, s.quantity,s.productid, s.userid, (p.price * s.quantity) as total
            FROM App\Entity\Shopcart s, App\Entity\Product p
            WHERE s.productid = p.id and s.userid=:userid
')
            ->setParameter('userid',$userid);
        return $query->getResult();
    }

}
Jakumi
  • 8,043
  • 2
  • 15
  • 32
  • Does it report the same error if you [explicitly define an expression](https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#fetch-via-an-expression)? – El_Vanja Nov 30 '20 at 14:55
  • Yes, I try that but I get same error.Moreover, there is no problem with the 'new' method at controller. – Ahmet Varan Nov 30 '20 at 15:49
  • Well, that's expected, since `new` doesn't use the ParamConverter. I presume you built `Shopcart` with the `make:entity` command which automatically created the repo and setup an `id` property? – El_Vanja Nov 30 '20 at 16:24
  • what parameter did you pass to route of delete and edit ? can you copy pate the url in the brower ? – hous Nov 30 '20 at 16:40
  • 1
    Is [this question](https://stackoverflow.com/questions/51521607/symfony4-object-not-found-by-the-paramconverter-annotation-404-error) of any help? – El_Vanja Nov 30 '20 at 18:46
  • please tell us, which exact uri you're accessing and what results you were expecting. as far as I can tell, you have overlapping route definitions (specifically, the `show` route might override the `new` route, rendering the new route inactive). – Jakumi Dec 01 '20 at 07:15
  • this url is my route on browser when I click delete icon. "http://127.0.0.1:8000/shopcart/1". I tried use paramconverter or requirement but I cant solve. – Ahmet Varan Dec 01 '20 at 11:30
  • Problem solved. Source of error is wrong sql query. – Ahmet Varan Dec 03 '20 at 12:30

1 Answers1

0

I think the problem is that you have two delete functions. The del function is a copy of the delete function. If you remove 'del' function your problem will be solved. The 'del' function override the route oh other functions.