0
我試着將產品添加到當前登錄的用戶購物車在我CartController,但是當我點擊「加入購物車」按鈕,它會引發以下異常:警告:無效參數
爲的foreach()提供無效參數
這裏是我的addToCart功能:
/**
* @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');
}
嘗試:'$產品= $請求 - >獲取( '產品') - >所有();' –
調用一個成員函數的所有()上的空 –
那麼' $ request-> get('products')'提供一個空數組......你確定get('products')'有效嗎? –