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

发布于 2024-11-08 15:24:45 字数 1061 浏览 0 评论 0原文

我收到来自外部站点的请求,其中包含一些产品 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) 效果很好,但我无法再影响产品的数量。

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

谢谢

I get a request from an extrenal site containing some product ids.
In my module i try to load the products and add them to the shopping cart. I tried it with this code:

    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');
}

I can see in the system.log that it loads the products correctly. But after the redirect i have the second product in my cart twice. The first one is missing. Using $cart->addProductsByIDs($ids) works great but then i cant influence the quantity of the products anymore.

Does someone know what i am doing wrong and give me a hint?

Thx

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

单调的奢华 2024-11-15 15:24:45

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

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 中

I had the same problem and I fixed it by loading the product model inside every loop:

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');
}

I then have an "Add all items to cart" button which executes the following Javascript code:

<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);
}


For this to be able to work, I put an extra product_id attribute on the quantity textbox, such as:

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

and the whole list of products is inside a div with ID product-listing-table

热风软妹 2024-11-15 15:24:45

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

$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);

也就是说,您的错误并不会让您听起来像您实际上在 这个区域。我无法想象会是这样,但是每次将产品添加到购物车时是否都需要保存购物车模型?值得一试。

Just checked with some custom add to cart code that I've got, and confirmed is working correctly, and the only difference I have is:

$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);

That said, your error doesn't make it sound like you're actually having trouble in this area. I can't imagine it would be this, but is it possible that the cart model needs to be save()d every time you add a product to the cart? It's worth a punt.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文