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

发布于 2024-11-12 07:59:34 字数 1373 浏览 4 评论 0原文

我尝试使用 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 中不存在此选项。

任何帮助表示赞赏。

好吧,乔纳森,那就是:

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-牛顿艺术家丙烯酸树脂/ http://www.polymexint.com/nouvelle-montana-black-blk-400ml.html

@Oliver:检查您的回复

I try to use that http://sourceforge.net/projects/massaddtocart/

It is exactly what I want, but it shows this error:

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

I want to to add multiple simple products with different qty to cart by one click. this option does not exist in Magento.

Any help is appreciated.

OK Jonathan, that is:

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

some exemples for what I want to get:
http://www.dickblick.com/products/winsor-and-newton-artists-acrylics/
http://www.polymexint.com/nouvelle-montana-black-blk-400ml.html

@Oliver: checking your response

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

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

发布评论

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

评论(2

哽咽笑 2024-11-19 07:59:34

还在寻找吗?找到了这个:

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

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

/***编辑****/

好吧,“不被认为是一个糟糕的答案”,这就是您应该如何实施解决方案。所有代码都不是我的作品,归功于 Uni-Man、Nexus Rex 和 Magento 论坛的人员:)

代码有详细记录。它在名称空间“Company”中创建一个完整的 Magento 扩展,名称为“Module”。

首先,在 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>

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

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

在底部插入:

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

您在这里要做的是:
- 生成第二个“添加到购物车”按钮,与顶部的按钮相同
- 关闭表单

当商品添加到购物车时,通常 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> 

这是做什么的:
- 将调用购物车控制器替换为调用自己的多添加控制器
- 注册助手
- 将路由器应用于前端

请告诉我是否需要更多相关文档。

still searching? Found this one:

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

Seems to work in current versions, though I haven't tested it yet. If you solved it, at least future searchers will know where to find it!

/***EDIT****/

Well, to "not be considered a poor answer", this how you should implement the solution. None of the code is my work, creds to Uni-Man, Nexus Rex and the Magento Forum guys :)

The code is well documented. It creates a fullworthy Magento extension in the namespace "Company" with the name "Module".

First, implement the helper in 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);
        }
    } 

Next, you will need to do some template-changes. Copy the file app/design/base/default/templates/catalog/list.phtml to app/design/default/default/templates/catalog/list.phtml. This makes sure that, once the extension is no longer wanted, you/your client can go back to the normal list view without coding.
Modify the new list.phtml file as follows:

After

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

add

<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> 

(This will open the form; all following items will add input boxes for quantity, so you can put all items in the cart using one sole button. This is put here, too.)

Scrolling down, you will find the area where normally the "Add To Cart" button is generated:

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

Replace the content of the if-block with:

<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>

This is the input-field for the quantity.
To close the -tag, insert after

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

at the bottom:

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

What you do here is:
- generate a second "Add To cart"-Button, identical with the one on top
- close the form

When an item ist added to the cart, normally Magento will call the Checkout_CartController. We have to modify this one in order to add not just one, but all items to the cart in the deserved quantity.

Therefore, add the file app/code/local/Company/Module/controllers/Checkout/CartController.php and fill in this:

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

We are overriding the existing Mage Core class with our own, resulting in the use of our controller for this purpose.

You will also have to add the module's config.xml as usual in app/code/local/Company/Module/etc/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> 

What this does:
- replaces call to cart controller with call to own multiadd controller
- registers helper
- applies router to frontend

Please tell me if more documentation on this is needed.

南城追梦 2024-11-19 07:59:34

有一种更简单的方法可以使用 jQuery/Javascript 来完成此操作。页面上的所有产品均位于

  • 标签中。这些标签有一个名为 data-product-id 的属性,其中包含每个产品的数字 ID。另外,我确信您知道可以使用诸如 http://www.yoursite.com/checkout/cart/add?product=1&lated_product=2 之类的 URL 将多个产品添加到购物车, 3(将数字 1,2 和 3 替换为您自己的产品 ID。)
  • 如果您有一个产品页面,我们可以使用 jQuery/JavaScript 生成一个 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>
    

    就是这样!

    There's an easier way to do this with jQuery/Javascript. All products on the page are in <li> tags. These tags have an attribute called data-product-id which contain the numeric ID of each product. Also, I'm sure you know that you can add multiple products to a shopping cart using a URL such as http://www.yoursite.com/checkout/cart/add?product=1&related_product=2,3 (Replace the numbers 1,2 and 3 with your own product ID's.)

    Knowing this if you have a page of products we can use jQuery/JavaScript to generate a URL that gets all the product ID's for each product on the page, and place them accordingly within a URL like the above.

    To accomplish this, first, make sure you have jQuery added to your site:

    <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>
    

    Now, add the following script - there are notes to let you know what each variable and function does:

    <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>
    

    Now, create a link with the id of productlink.

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

    That's it!

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