Add multiple products to cart - Magento

10,732

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.

Share:
10,732
Newbie
Author by

Newbie

Updated on June 04, 2022

Comments

  • Newbie
    Newbie almost 2 years

    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