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

Magento-使用循环将产品添加到购物车,magento,product,cart,Magento,Product,Cart,我从一个包含一些产品ID的外部站点收到一个请求。 在我的模块中,我尝试加载产品并将其添加到购物车中。我用以下代码进行了尝试: public function indexAction() { $ids = explode(',', $this->getRequest()->getParam('products')); Mage::log('ADDING PRODUCTS'); $cart = Mage::getModel('checkout/cart

我从一个包含一些产品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->addProductsByds($ids)效果很好,但是我不能再影响产品的数量了

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


Thx

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

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

我刚刚用一些定制的购物车添加代码检查了一下,确认它工作正常,唯一的区别是:

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

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

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');
}
公共函数AddMultipleItemsAction(){
$products=explode(',',$this->getRequest()->getParam('products');
$Quantilities=explode(',',$this->getRequest()->getParam('Quantilities');
$numProducts=计数($products);
$cart=$this->_getCart();
对于($i=0;$igetTypeId()==Mage\U目录\U模型\U产品\U类型::类型\U简单){
试一试{
$eventArgs=array(
“产品”=>$pModel,
“数量”=>美元数量,
“附加_id”=>array(),
'request'=>this->getRequest(),
'response'=>this->getResponse(),
);
Mage::dispatchEvent('checkout\u cart\u before\u add',$eventArgs);
$cart->addProduct($pModel,array('product'=>$product\u id,'qty'=>$quantity));
Mage::dispatchEvent('checkout\u cart\u after\u add',$eventArgs);
Mage::dispatchEvent('checkout\u cart\u add\u product',数组('product'=>$pModel));
$message=$this->(已成功将“%s”添加到您的购物车中,$pModel->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
}捕获(法师核心例外$e){
if(Mage::getSingleton('checkout/session')->getUseNotice(true)){
Mage::getSingleton('checkout/session')->addNotice($pModel->getName()。:'。$e->getMessage());
}
否则{
Mage::getSingleton('checkout/session')->addError($pModel->getName()。:'。$e->getMessage());
}
}捕获(例外$e){
Mage::getSingleton('checkout/session')->addException($e,$this->uuuu('cannotadditestoshoppingcart'));
}
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
$this->_重定向('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);
}

函数addAllItemsToCart(){
productsArr=新数组();
quantitiesArr=新数组();
$$('#产品列表表.qty')。每个(
功能(输入、索引){
productsArr[index]=encodeURIComponent(input.readAttribute('product_id'));
quantitiesArr[index]=encodeURIComponent(输入值);
}
);
var url='/MyModule/Cart/AddMultipleItems/products/'+productsArr.join(',')+'/quanties/'+quantitiesArr.join(',')+'/';
设置位置(url);
}


为了使其能够工作,我在quantity文本框中添加了一个额外的product_id属性,例如:

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

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

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');
}
公共函数AddMultipleItemsAction(){
$products=explode(',',$this->getRequest()->getParam('products');
$Quantilities=explode(',',$this->getRequest()->getParam('Quantilities');
$numProducts=计数($products);
$cart=$this->_getCart();
对于($i=0;$igetTypeId()==Mage\U目录\U模型\U产品\U类型::类型\U简单){
试一试{
$eventArgs=array(
“产品”=>$pModel,
“数量”=>美元数量,
“附加_id”=>array(),
'request'=>this->getRequest(),
'response'=>this->getResponse(),
);
Mage::dispatchEvent('checkout\u cart\u before\u add',$eventArgs);
$cart->addProduct($pModel,array('product'=>$product\u id,'qty'=>$quantity));
Mage::dispatchEvent('checkout\u cart\u after\u add',$eventArgs);
Mage::dispatchEvent('checkout\u cart\u add\u product',数组('product'=>$pModel));
$message=$this->(已成功将“%s”添加到您的购物车中,$pModel->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
}捕获(法师核心例外$e){
if(Mage::getSingleton('checkout/session')->getUseNotice(true)){
Mage::getSingleton('checkout/session')->addNotice($pModel->getName()。:'。$e->getMessage());
}
否则{
Mage::getSingleton('checkout/session')->addError($pModel->getName()。:'。$e->getMessage());
}
}捕获(例外$e){
Mage::getSingleton('checkout/session')->addException($e,$this->u_;('无法将项目添加到购物车'