Advertisement
Guest User

Add To Car Function

a guest
Apr 25th, 2017
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. /**
  2. * @Route("/cart/add", name="cart_add")
  3. */
  4. public function addToCartAction(Request $request)
  5. {
  6. $manager = $this->getDoctrine()->getManager();
  7. $currentUserId = $this->get('security.token_storage')->getToken()->getUser();
  8. $session = $this->get('session');
  9. $id_cart = $session->get('id_cart', false);
  10.  
  11. if (!$id_cart) {
  12. $cart = new Cart();
  13. $cart->setUserId($currentUserId);
  14. $cart->setDateCreated(new \DateTime());
  15. $cart->setDateUpdated(new \DateTime());
  16.  
  17. $manager->persist($cart);
  18. $manager->flush();
  19. $session->set('id_cart', $cart->getId());
  20. }
  21.  
  22. $cart = $this->getDoctrine()->getRepository('AppBundle:Cart')->find($session->get('id_cart', false));
  23.  
  24. var_dump($products = $request->get('products'));
  25.  
  26. foreach ($products as $id_product) {
  27. $product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($id_product);
  28.  
  29. if($product) {
  30. $cartProduct = new CartProduct();
  31. $cartProduct->setCart($cart);
  32. $cartProduct->setProduct($product);
  33. $cartProduct->setQuantity(1);
  34.  
  35. $manager->persist($cartProduct);
  36. }
  37. }
  38. $cart->setDateUpdated(new \DateTime());
  39. $manager->persist($cart);
  40. $manager->flush();
  41.  
  42. return $this->redirectToRoute('cart_list');
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement