Magento - 使用循环将产品添加到购物车

时间:2011-05-19 16:04:36

标签: magento product cart

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

    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)效果很好,但我不能再影响产品的数量了。

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

THX

2 个答案:

答案 0 :(得分:3)

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

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 :(得分:1)

刚刚查看了我已经获得的一些自定义添加到购物车代码,并确认工作正常,我唯一的区别是:

$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?值得一试。