Magento utility: add multiple products to cart from catalog page
Magento utility: add multiple simple/configurable products to cart from catalog page
In the endless struggle to make our Magento stores more user-friendly, often we want to enable the customers to add multiple products in the catalog view page directly into shopping cart. This is a very convenient feature for wholesale websites, since the customer does not have to go through every single product detail page.
(This is a developer’s guide.)
We are shooting for a clean and direct fix, which I classify as a Magento utility.
The first step is to modify the /catalog/category/view.phtml, for each product in the product list, insert a form:
[codesyntax lang=”php”]
<form action="<?php echo $this->getBaseUrl() ?>utility/expressCart/add" method="post" > <input type="hidden" name="addToCartProductId" value="<?php echo $product->getId() ?>" /> <p><?php echo $inputString ?></p> <p><input type="submit" value="<?php echo $this->__('Add to Cart') ?>"></p> </form>
[/codesyntax]
Where the $inputString is the input field for item ID and quantity. It can be prepared in advance:
[codesyntax lang=”php” lines=”fancy”]
<?php $inputString .= '<input type="text" name="addToCart['.$_item->getId().']" value="" size="1" /> '; ?>
[/codesyntax]
Then in the utility controller, add all products to cart (this is for Configurable product, simple product is easier to handle):
[codesyntax lang=”php”]
foreach ( $addToCartArray as $itemId => $itemQty ) { $product = Mage::getModel ( 'catalog/product' )->setStoreId ( $storeId )->load ( $_POST ['addToCartProductId'] ); $simpleProduct = Mage::getModel ( 'catalog/product' )->setStoreId ( $storeId )->load ( $itemId ); $params = array ('product' => $_POST ['addToCartProductId'], 'super_attribute' => array ($attributeId => $simpleProduct->getData ( $attributeCode ) ), 'qty' => $itemQty ); $cart->addProduct ( $product, $params ); $cart->save (); }
[/codesyntax]
Since we are handling configurable items, we must prepare the attribute code:
[codesyntax lang=”php”]
$product = Mage::getModel ( 'catalog/product' )->setStoreId ( $storeId )->load ( $_POST ['addToCartProductId'] ); $_attributes = $product->getTypeInstance ( true )->getConfigurableAttributes ( $product ); foreach ( $_attributes as $_attribute ) { $attributeId = $_attribute->getAttributeId (); } $attributeCode = $product->getTypeInstance ( true )->getAttributeById ( $attributeId, $product )->getAttributeCode ();
[/codesyntax]
Final remark, since all action are handle behind the scene, we need to send the customer either to the previous page or shopping cart. Move to the cart should be the default behavior, in case you want o go back to previous page:
[codesyntax lang=”php” lines=”fancy”]
$this->getResponse()->setRedirect($this->_getRefererUrl());
[/codesyntax]