I’m stuck on coming up with the logic to say do this once. I need to create a ‘cart’ for the user and then use that newly created ‘cart’ to add the products that the user selected to their ‘cart’.
I’m not using SESSION variables, I know that would be a solution though.
Basically I’m trying to say this:
IF a User HAS a CART CREATED FOR THEM
then
PERSIST their SELECTED PRODUCTS to the DB in THEIR CART
Any help is appreciated, Thanks to All.
/**
* Creates the option to 'add product to cart'.
*
* @Route("/{id}/addToCart", name="product_addToCart")
* @Method("GET")
* @Template()
*/
public function addToCartAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('ShopBundle:Product')->find($id);
$product->getId();
$product->getName();
$product->getPrice();
// --------------------- assign added products to userCart id ------------------------ //
$cart = new UserCart();
$quantity = new Quantity();
// Set Time Product was Added
$cart->setTimestamp(new \DateTime());
// Set Quantity Purchased
$quantity->setQuantity(4);
// Set Submitted
$cart->setSubmitted(false);
if ($this->checkUserLogin()) {
$this->addFlash('notice', 'Login to create a cart');
} else {
$cart->setUser($this->getUser()); // Sets the User ONCE
$cart->addQuantity($quantity); // Add Quantity ONCE
$quantity->setUserCart($cart); // Create a UserCart ONCE
$this->addFlash('notice', 'The product: '.$product->getName().' has been added to the cart!');
$quantity->setProduct($product); // Sets the Product to Quantity Association ONCE
$em->persist($product);
$em->persist($cart);
$em->persist($quantity);
$em->flush();
}
return $this->redirectToRoute('product');
}
答案 0 :(得分:0)
Well, the easiest way to do this is by simply trying to fetch the user cart, and only if one doesn't exist, creating a new one. So instead of:
$cart = new UserCart();
You'd have to write something along the lines of:
$cart = $em->getRepository('ShopBundle:UserCart')->findOneBy([
'user' => $this->getUser()
]);
if (!$cart) {
$cart = new UserCart();
// Anything else you need to do when setting up a new cart goes here
}
You probably want to check if the user is logged in before looking for his cart though. And remember to empty/delete the cart once the transaction has been made or canceled.