添加多个产品到购物车 - Magento

时间:2011-05-31 09:00:39

标签: magento add cart product

我尝试使用http://sourceforge.net/projects/massaddtocart/

这正是我想要的,但它显示了这个错误:

Fatal error: Call to a member function setProduct() on a non-object in [...]/app/code/local/BD83/MassAddToCart/Helper/Data.php on line 20

我想通过一次点击将多个具有不同数量的简单产品添加到购物车中。 Magento中不存在此选项。

感谢任何帮助。

好的Jonathan,就是:

public function getButtonHtml(Mage_Catalog_Model_Product $product)
{
    if ($product->getId() && !$product->getIsComposite()) {
        $qtyBlock = Mage::app()->getLayout()
            ->getBlock('bd83.massaddtocart.catalog.product.list.item.button');
        $qtyBlock->setProduct($product) // **LINE 20**
            ->setProductId($product->getId())
            ->setMinQty(Mage::getStoreConfig(self::XML_PATH_MIN_QTY))
            ->setDefaultQty(Mage::getStoreConfig(self::XML_PATH_DEFAULT_QTY))
            ->setMaxQty(Mage::getStoreConfig(self::XML_PATH_MAX_QTY));
        return $qtyBlock->toHtml();
    }
    return '';
}

我希望获得的一些例子: http://www.dickblick.com/products/winsor-and-newton-artists-acrylics/ http://www.polymexint.com/nouvelle-montana-black-blk-400ml.html

@Oliver:检查您的回复

2 个答案:

答案 0 :(得分:4)

还在搜索吗?找到这个:

http://www.magentocommerce.com/boards/viewthread/9797

似乎在当前版本中工作,但我还没有测试过。如果你解决了它,至少未来的搜索者会知道在哪里找到它!

/ *** **** EDIT /

好吧,为了“不被认为是一个糟糕的答案”,你应该如何实施解决方案。这些代码都不是我的作品,对Uni-Man,Nexus Rex和Magento论坛的人都很有信心:))

代码记录良好。它在名称为“Module”的命名空间“Company”中创建了一个值得信赖的Magento扩展。

首先,在app / code / local / Company / Module / helper / Data.php中实现帮助:

    <?php
    class Company_Module_Helper_Multiple extends Mage_Core_Helper_Url
    {
        /**
         * Return url to add multiple items to the cart
         * @return  url
         */
        public function getAddToCartUrl()
        {
            if ($currentCategory = Mage::registry('current_category')) {
                $continueShoppingUrl = $currentCategory->getUrl();
            } else {
                $continueShoppingUrl = $this->_getUrl('*/*/*', array('_current'=>true));
            }

            $params = array(
                Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => Mage::helper('core')->urlEncode($continueShoppingUrl)
            );

            if ($this->_getRequest()->getModuleName() == 'checkout'
                && $this->_getRequest()->getControllerName() == 'cart') {
                $params['in_cart'] = 1;
            }
            return $this->_getUrl('checkout/cart/addmultiple', $params);
        }
    } 

接下来,您需要进行一些模板更改。将文件app / design / base / default / templates / catalog / list.phtml复制到app / design / default / default / templates / catalog / list.phtml。这样可以确保一旦不再需要扩展,您/您的客户端就可以返回到正常列表视图而无需编码。 修改新的list.phtml文件,如下所示:

<?php echo $this->getToolbarHtml(); ?>

添加

<form action="<?php echo $this->helper( 'Module/multiple' )->getAddToCartUrl() ?>" method="post" id="product_addtocart_form">
<button class="form-button" onclick="productAddToCartForm.submit()"><span><?php echo $this->__('Add Items to Cart') ?></span></button> 

(这将打开表格;以下所有项目都会添加数量输入框,因此您可以使用一个单一按钮将所有商品放入购物车。这也放在这里。)

向下滚动,您会找到通常会生成“添加到购物车”按钮的区域:

<?php if($_product->isSaleable()): ?> 

将if块的内容替换为:

<fieldset class="add-to-cart-box">
  <input type="hidden" name="products[]" value="<?php echo $_product->getId() ?>" />
  <legend><?php echo $this->__('Add Items to Cart') ?></legend>
  <span class="qty-box"><label for="qty<?php echo $_product->getId() ?>"><?php echo $this->__('Qty') ?>:</label>
  <input name="qty<?php echo $_product->getId() ?>" type="text" class="input-text qty" id="qty<?php echo $_product->getId() ?>" maxlength="12" value="" /></span>
</fieldset>

这是数量的输入字段。 要关闭-tag,请在

之后插入
<?php echo $this->getToolbarHtml() ?>

在底部:

<button class="form-button" onclick="productAddToCartForm.submit()"><span><?php echo $this->__('Add Items to Cart') ?></span></button>
</form> 

你在这里做的是: - 生成第二个“添加到购物车”-Button,与顶部相同 - 关闭表格

当项目被添加到购物车时,通常Magento将调用Checkout_CartController。我们必须修改这个,以便不仅仅将一个,而且所有项目添加到购物车中。

因此,添加文件app / code / local / Company / Module / controllers / Checkout / CartController.php并填写:

> require_once 'Mage/Checkout/controllers/CartController.php';
> 
> class Company_Module_Checkout_CartController extends
> Mage_Checkout_CartController {

>     public function addmultipleAction()
>     {
>         $productIds = $this->getRequest()->getParam('products');
>         if (!is_array($productIds)) {
>             $this->_goBack();
>             return;
>         }
> 
>         foreach( $productIds as $productId) {
>             try {
>                 $qty = $this->getRequest()->getParam('qty' . $productId, 0);
>                 if ($qty <= 0) continue; // nothing to add
>                 
>                 $cart = $this->_getCart();
>                 $product = Mage::getModel('catalog/product')
>                     ->setStoreId(Mage::app()->getStore()->getId())
>                     ->load($productId)
>                     ->setConfiguredAttributes($this->getRequest()->getParam('super_attribute'))
>                     ->setGroupedProducts($this->getRequest()->getParam('super_group', array()));
>                 $eventArgs = array(
>                     'product' => $product,
>                     'qty' => $qty,
>                     'additional_ids' => array(),
>                     'request' => $this->getRequest(),
>                     'response' => $this->getResponse(),
>                 );
>     
>                 Mage::dispatchEvent('checkout_cart_before_add', $eventArgs);
>     
>                 $cart->addProduct($product, $qty);
>     
>                 Mage::dispatchEvent('checkout_cart_after_add', $eventArgs);
>     
>                 $cart->save();
>     
>                 Mage::dispatchEvent('checkout_cart_add_product', array('product'=>$product));
>     
>                 $message = $this->__('%s was successfully added to your shopping cart.', $product->getName());    
>                 Mage::getSingleton('checkout/session')->addSuccess($message);
>             }
>             catch (Mage_Core_Exception $e) {
>                 if (Mage::getSingleton('checkout/session')->getUseNotice(true)) {
>                     Mage::getSingleton('checkout/session')->addNotice($product->getName() . ': ' . $e->getMessage());
>                 }
>                 else {
>                     Mage::getSingleton('checkout/session')->addError($product->getName() . ': ' . $e->getMessage());
>                 }
>             }
>             catch (Exception $e) {
>                 Mage::getSingleton('checkout/session')->addException($e, $this->__('Can not add item to shopping cart'));
>             }
>         }
>         $this->_goBack();
>     } }

我们正在使用我们自己的Mage Core类覆盖它,导致我们的控制器用于此目的。

您还必须像往常一样在app / code / local / Company / Module / etc / config.xml中添加模块的config.xml:

 <?xml version="1.0"?>
    <config>
        <modules>
            <Company_Module>
                <version>0.1.0</version>
            </Company_Module>
        </modules>
        <global>
            <rewrite>
                <company_module_checkout_cart>
                    <from><![CDATA[#^/checkout/cart/addmultiple/.*$#]]></from>
                    <to>/module/checkout_cart/addmultiple/</to>
                </company_module_checkout_cart> 
            </rewrite>
            <helpers>
                <Module>
                    <class>Company_Module_Helper</class>
                </Module>
            </helpers>
        </global>
        <frontend>
            <routers>
                <company_module>
                    <use>standard</use>
                    <args>
                        <module>Company_Module</module>
                        <frontName>module</frontName>
                    </args>
                </company_module>
            </routers>
        </frontend>
    </config> 

这是做什么的: - 通过调用自己的multiadd控制器替换对购物车控制器的调用 - 登记助手 - 将路由器应用于前端

如果需要更多相关文档,请告诉我。

答案 1 :(得分:0)

使用jQuery / Javascript有一种更简单的方法。页面上的所有产品均为<li>标记。这些标记具有名为data-product-id的属性,其中包含每个产品的数字ID。另外,我相信您知道可以使用http://www.yoursite.com/checkout/cart/add?product=1&related_product=2,3等网址将多个产品添加到购物车中(将数字1,2和3替换为您自己的产品ID)。

了解这一点,如果您有一个产品页面,我们可以使用jQuery / JavaScript生成一个URL,该URL可以获取页面上每个产品的所有产品ID,并相应地将它们放置在如上所述的URL中。

要实现此目的,首先要确保已将jQuery添加到您的网站:

<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

现在,添加以下脚本 - 有一些注释让您知道每个变量和函数的作用:

<script>
$(document).ready(function() {
//Function to get all product ID's, & create a URL that will add all the items
function generateUrl() {
    //the variable 'firstItem' will find the first Product ID in an li tag
    var firstItem = $("li").first().attr("data-product-id");
    //the variable 'otherItem' will earch all other li's, and grab their product ID's
    var otherItem = $('li').nextAll().map(function() {return $(this).attr('data-product-id');}).get();
    //the newURL creates the URL that adds the products to the cart; replace the site URL with your own.
    var newUrl = 'http://shop.yoursite.com/checkout/cart/add?product=' + firstItem + '&related_product=' + otherItem;
    //this seeks a link with the ID of "productlink", then will add the URL generated from newURL to the href tag
    $('#productlink').attr("href" , newUrl);
}
//start function!
generateUrl();

});

</script>

现在,创建一个ID为productlink的链接。

<a href="" id="productlink">Add All Items To Cart</a>

就是这样!

相关问题