【问题标题】:Magento - Adding products to cart using a loopMagento - 使用循环将产品添加到购物车
【发布时间】:2011-05-19 16:04:35
【问题描述】:

我收到来自外部网站的请求,其中包含一些产品 ID。 在我的模块中,我尝试加载产品并将它们添加到购物车中。我用这段代码试了一下:

    public function indexAction() {
    $ids = explode(',', $this->getRequest()->getParam('products'));

    Mage::log('ADDING PRODUCTS');

    $cart = Mage::getModel('checkout/cart');
    $cart->init();

    $pModel = Mage::getSingleton('catalog/product');

    //$cart->addProductsByIDs($ids);

    foreach ($ids as $id) {

        Mage::log('Loading: ' . $id);

        $product = $pModel->load($id);

        Mage::log('Loaded: ' . $product->getId());

        try {
            $cart->addProduct($product, array('qty' => '1'));
        } catch (Exception $e) { 
            Mage::log($e);
            continue; 
        }
    }

    $cart->save();

    if ($this->getRequest()->isXmlHttpRequest()) {
        exit('1');
    }

    $this->_redirect('checkout/cart');
}

我可以在 system.log 中看到它正确加载了产品。但是在重定向之后,我的购物车中有第二个产品两次。第一个不见了。使用 $cart->addProductsByIDs($ids) 效果很好,但我不能再影响产品的数量了。

有人知道我做错了什么并给我提示吗?

谢谢

【问题讨论】:

    标签: magento product cart


    【解决方案1】:

    我遇到了同样的问题,我通过在每个循环中加载产品模型来解决它:

    public function AddMultipleItemsAction() {
        $products = explode(',', $this->getRequest()->getParam('products'));
        $quantities = explode(',', $this->getRequest()->getParam('quantities'));
        $numProducts = count($products);
        $cart = $this->_getCart();
        for($i=0;$i<$numProducts;$i++) {
            $product_id = $products[$i];
            $quantity = $quantities[$i];
            if ($product_id == '') continue;
            if(!is_numeric($quantity) || $quantity <= 0) continue;
            $pModel = Mage::getModel('catalog/product')->load($product_id);
            if($pModel->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) {
                try {
                    $eventArgs = array(
                        'product' => $pModel,
                        'qty' => $quantity,
                        'additional_ids' => array(),
                        'request' => $this->getRequest(),
                        'response' => $this->getResponse(),
                    );
                    Mage::dispatchEvent('checkout_cart_before_add', $eventArgs);
                    $cart->addProduct($pModel, array('product'=>$product_id,'qty' => $quantity));
                    Mage::dispatchEvent('checkout_cart_after_add', $eventArgs);
                    Mage::dispatchEvent('checkout_cart_add_product', array('product'=>$pModel));
                    $message = $this->__('%s was successfully added to your shopping cart.', $pModel->getName());
                    Mage::getSingleton('checkout/session')->addSuccess($message);
                } catch (Mage_Core_Exception $e) {
                    if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
                        Mage::getSingleton('checkout/session')->addNotice($pModel->getName() . ': ' . $e->getMessage());
                    }
                    else {
                        Mage::getSingleton('checkout/session')->addError($pModel->getName() . ': ' . $e->getMessage());
                    }
                } catch (Exception $e) {
                    Mage::getSingleton('checkout/session')->addException($e, $this->__('Can not add item to shopping cart'));
                }
            }
        }
        $cart->save();
        $this->_getSession()->setCartWasUpdated(true);
        $this->_redirect('checkout/cart');
    }
    

    然后我有一个“将所有商品添加到购物车”按钮,该按钮执行以下 Javascript 代码:

    <script type="text/javascript">
    function addAllItemsToCart() {
        productsArr = new Array();
        quantitiesArr = new Array();
        $$('#product-listing-table .qty').each(
            function (input, index) {
                productsArr[index] = encodeURIComponent(input.readAttribute('product_id'));
                quantitiesArr[index] = encodeURIComponent(input.value);
            }
        );
        var url = '/MyModule/Cart/AddMultipleItems/products/'+productsArr.join(',')+'/quantities/'+quantitiesArr.join(',')+'/';
        setLocation(url);
    }
    


    为了使它能够工作,我在数量文本框上添加了一个额外的 product_id 属性,例如:

    <input type="text" size="2" product_id="<?php echo $_product->getId();?>" name="productqty_<?php echo $_product->getId();?>" class="qty" />
    

    整个产品列表都在一个 ID 为 product-listing-table

    的 div 中

    【讨论】:

    • +1。我遇到了同样的问题,在每个循环中加载产品模型也对我有用,谢谢!我只需要弄清楚为什么每个项目被添加 5 次而不是一次,想知道你是否遇到了同样的问题?
    【解决方案2】:

    刚刚检查了我拥有的一些自定义添加到购物车代码,并确认工作正常,我唯一的区别是:

    $cart->addProduct($product, array(
        'qty'     => 1,
        'product' => $product->getId(),
        'uenc'    => Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl())
    ));
    
    // Also make sure we know that the cart was updated
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    

    也就是说,您的错误并没有让人觉得您在 这个 区域确实遇到了麻烦。我无法想象会是这样,但是每次您将产品添加到购物车时,购物车模型是否可能需要为save()d?值得一试。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2017-05-18
      • 2012-09-14
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 2012-06-09
      • 2014-05-10
      相关资源
      最近更新 更多