【问题标题】:Shopping Cart Bundle with Symfony2Symfony2 购物车捆绑包
【发布时间】:2012-08-27 22:01:21
【问题描述】:

我正在学习如何使用 Symfony2,同时为一家家族经营的葡萄酒进口商建立一个小型电子商务网站。慢慢地,我对 Symfony2 的概念有了了解,但在继续构建购物车捆绑包时,我不太确定什么是正确的(至少根据 Sf2 标准)来实现它。

我根据会话制作了简单的购物车捆绑包。

我的问题是,当我在购物车中添加产品时,它会一直工作,直到产品 id 为 0 到 9 并且产品数量会自动增加,但是在产品 id 为 10 之后,它的数量等于产品 id 而它应该是一个。而且也是错误的当我们要获取产品信息时,产品信息就来了。

我希望这不是一个太宽泛的问题。我很清楚,真正强大的购物车实施并非易事。

我的代码在这里:

  • CartController.php
    <?php
    
    namespace Webmuch\CartBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
    use Symfony\Component\HttpFoundation\Response;
    
    use Webmuch\ProductBundle\Entity\Product;
    
    /**
     * @Route("/cart")
     */
    class CartController extends Controller
    {
    /**
     * @Route("/", name="cart")
     */
    public function indexAction()
    {
        // get the cart from  the session
        $session = $this->getRequest()->getSession();
        // $cart = $session->set('cart', '');
        $cart = $session->get('cart', array());
    
        // $cart = array_keys($cart);
        // print_r($cart); die;
    
        // fetch the information using query and ids in the cart
        if( $cart != '' ) {
    
            foreach( $cart as $id => $quantity ) {
                      $productIds[] = $id;
    
            }           
    
            if( isset( $productIds ) )
            {
                $em = $this->getDoctrine()->getEntityManager();
                $product = $em->getRepository('WebmuchProductBundle:Product')->findById( $productIds );
            } else {
                return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
                    'empty' => true,
                ));
            }
    
    
    
            return $this->render('WebmuchCartBundle:Cart:index.html.twig',     array(
                'product' => $product,
            ));
        } else {
            return $this->render('WebmuchCartBundle:Cart:index.html.twig',     array(
                'empty' => true,
            ));
        }
    }
    
    
    /**
     * @Route("/add/{id}", name="cart_add")
     */
    public function addAction($id)
    {
        // fetch the cart
        $em = $this->getDoctrine()->getEntityManager();
        $product = $em->getRepository('WebmuchProductBundle:Product')->find($id);
        //print_r($product->getId()); die;
        $session = $this->getRequest()->getSession();
        $cart = $session->get('cart', array());
    
    
        // check if the $id already exists in it.
        if ( $product == NULL ) {
             $this->get('session')->setFlash('notice', 'This product is not     available in Stores');          
            return $this->redirect($this->generateUrl('cart'));
        } else {
            if( isset($cart[$id]) ) {
    
                $qtyAvailable = $product->getQuantity();
    
                if( $qtyAvailable >= $cart[$id]['quantity'] + 1 ) {
                    $cart[$id]['quantity'] = $cart[$id]['quantity'] + 1; 
                } else {
                    $this->get('session')->setFlash('notice', 'Quantity     exceeds the available stock');          
                    return $this->redirect($this->generateUrl('cart'));
                }
            } else {
                // if it doesnt make it 1
                $cart = $session->get('cart', array());
                $cart[$id] = $id;
                $cart[$id]['quantity'] = 1;
            }
    
            $session->set('cart', $cart);
            return $this->redirect($this->generateUrl('cart'));
    
        }
    }
    
    
    /**
     * @Route("/remove/{id}", name="cart_remove")
     */
    public function removeAction($id)
    {
        // check the cart
        $session = $this->getRequest()->getSession();
        $cart = $session->get('cart', array());
    
        // if it doesn't exist redirect to cart index page. end
        if(!$cart) { $this->redirect( $this->generateUrl('cart') ); }
    
        // check if the $id already exists in it.
        if( isset($cart[$id]) ) {
            // if it does ++ the quantity
            $cart[$id]['quantity'] = '0';
            unset($cart[$id]);
            //echo $cart[$id]['quantity']; die();
        } else {
            $this->get('session')->setFlash('notice', 'Go to hell');    
            return $this->redirect( $this->generateUrl('cart') );
        }
    
        $session->set('cart', $cart);
    
        // redirect(index page)
        $this->get('session')->setFlash('notice', 'This product is Remove');
        return $this->redirect( $this->generateUrl('cart') );
    }
    }
    

  • index.html.twig:
    {% block body %}
    <h1>"FLAIRBAG" SHOPPING-CART</h1>
    
    <ul class="thumbnails">
    
    {% if empty %}
    <h5>Your shopping cart is empty.</h5>
    {% endif %}
    {% set cart = app.session.get('cart') %}
    
    
    {% if product %}
    
    
    <ul class="thumbnails">
    {% if app.session.hasFlash('notice') %} 
    
     <divclass="flash-notice">
    
      {{app.session.flash('notice') }} 
      {{ app.session.removeFlash('notice') }}
    
     </div>
    
    {% endif %}         
    {% for key, item in cart %}
        <p>ID:{{ key }}</p>
         <p>Quantity:{{ item }}</p>
         <button class="btn btn-primary"><a href="{{ path('cart_remove', {'id':     key}) }}">Remove</a></button>
    
       {% for item in product %}
            <p>{{ item.title }}</p>
        <p>{{ item.preview }}</p>
    {% endfor %}
    
    
    
    {% endfor %}
    </ul>
    
    {% endif %}
    </ul>
    
    <a href="{{ path('products') }}">Products</a>
    
    {% endblock %}
    

    请帮帮我。

    谢谢!感谢您的帮助。

  • 【问题讨论】:

    标签: php session symfony twig


    【解决方案1】:

    问题出在您的购物车数组中。根据您的模板,您希望有一个具有这种结构的数组:

    cart {
        id => quantity
    }
    

    即,数组的键是产品的 id,值是数量

    但是在你的控制器中你可以这样做:

            $cart[$id] = $id;
            $cart[$id]['quantity'] = 1;
    

    这是一个非常不同的事情。你应该这样做:

            $cart[$id] = 1;
    

    并且在控制器中使用 $cart[$id]['quantity'] 的所有其他地方使用 $cart[$id] 代替。例如:

               $cart[$id] = $cart[$id] + 1; 
    

    编辑:

    在你的控制器中做:

        $em = $this->getDoctrine()->getEntityManager();
        foreach( $cart as $id => $quantity ) {
              $product[] = $em->getRepository('WebmuchProductBundle:Product')->findById($id)
        }           
    
        if( !isset( $product ) )
        {
            return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
                'empty' => true,
            ));
        }
    

    【讨论】:

    • 感谢它有效,但是当我们想在购物车中显示任何产品的标题或预览时,它会显示错误,并且每个产品 ID 中都会出现相同的标题。
    • findById 不会采用数组并返回该数组中具有 id 的所有项目。我会更新我的答案
    • 非常感谢,我设法让它工作了。你的回答很有帮助。再次感谢。
    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2012-09-14
    • 2011-10-25
    • 1970-01-01
    相关资源
    最近更新 更多