2016-04-04 30 views
-1

Bir keresinde bunu yapmak için mantıkla gelme konusunda takıldım. Kullanıcı için bir "sepet" oluşturmam ve ardından kullanıcının "sepetine" seçtiği ürünleri eklemek için yeni oluşturulan "sepet" i kullanmam gerekiyor.Bir kez nasıl yapılır

SESSION değişkenlerini kullanmıyorum, bunun bir çözüm olacağını biliyorum.

Temelde bunu söylemek çalışıyorum:

IF a User HAS a CART CREATED FOR THEM 

       then 

PERSIST their SELECTED PRODUCTS to the DB in THEIR CART 

Herhangi bir yardım takdir, Tüm sayesinde.

/** 
* 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'); 

} 

cevap

0

Eh, Biri yoksa yalnızca basit bir yenisini oluşturmak ve kullanıcı sepeti almaya çalışarak Bunu yapmanın en kolay yolu. Bunu yerine:

$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 
} 

Muhtemelen kullanıcı olsa onun arabası arayışına girmeden önce giriş yapmış olup olmadığını kontrol etmek istiyorum:

$cart = new UserCart(); 

Sen çizgisinde bir şeyler yazmak gerekir. İşlem yapıldıktan veya iptal edildikten sonra sepeti boşaltmayı/silmeyi unutmayın.

İlgili konular