Rumen Panchev
Rumen Panchev

Reputation: 498

Invalid argument supplied for foreach in Symfony Controller

Im trying to add products to current logged in user cart in my CartController, but when i click the "Add To Cart" Button it throws the following exception: Warning:

Invalid argument supplied for foreach()

Here's my addToCart Function:

/**
     * @Route("/cart/add", name="cart_add")
     */
    public function addToCartAction(Request $request)
    {
        $manager = $this->getDoctrine()->getManager();
        $currentUserId = $this->get('security.token_storage')->getToken()->getUser();
        $session = $this->get('session');
        $id_cart = $session->get('id_cart', false);

        if (!$id_cart) {
            $cart = new Cart();
            $cart->setUserId($currentUserId);
            $cart->setDateCreated(new \DateTime());
            $cart->setDateUpdated(new \DateTime());

            $manager->persist($cart);
            $manager->flush();
            $session->set('id_cart', $cart->getId());
        }

        $cart = $this->getDoctrine()->getRepository('AppBundle:Cart')->find($session->get('id_cart', false));

        $products = $request->get('products');

        foreach ($products as $id_product) {
            $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($id_product);

            if($product) {
                $cartProduct = new CartProduct();
                $cartProduct->setCart($cart);
                $cartProduct->setProduct($product);
                $cartProduct->setQuantity(1);

                $manager->persist($cartProduct);
            }
        }
        $cart->setDateUpdated(new \DateTime());
        $manager->persist($cart);
        $manager->flush();

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

Upvotes: 1

Views: 4080

Answers (1)

Maxime Perrimond
Maxime Perrimond

Reputation: 58

You should add a default value when you get a parameter to avoid those kind of errors:

$products = $request->get('products', []);

Upvotes: 1

Related Questions