0% found this document useful (0 votes)
166 views5 pages

Add Multiple Products To Cart Magento

The document describes how to add multiple simple products to the cart with different quantities in one click using a Magento extension. It provides code for a helper class, template modifications, and a controller class override that allows submitting a form to add multiple products to the cart at once by passing an array of product IDs and quantities to the checkout/cart controller.

Uploaded by

Puneet Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
166 views5 pages

Add Multiple Products To Cart Magento

The document describes how to add multiple simple products to the cart with different quantities in one click using a Magento extension. It provides code for a helper class, template modifications, and a controller class override that allows submitting a form to add multiple products to the cart at once by passing an array of product IDs and quantities to the checkout/cart controller.

Uploaded by

Puneet Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

signup

login

tour

help

stackoverflowcareers

Signup

StackOverflowisacommunityof4.7millionprogrammers,justlikeyou,[Link],itonlytakesaminute:

AddmultipleproductstocartMagento

Itrytousethat[Link]
ItisexactlywhatIwant,butitshowsthiserror:
Fatalerror:CalltoamemberfunctionsetProduct()onanonobjectin
[...]/app/code/local/BD83/MassAddToCart/Helper/Data.phponline20

[Link].
Anyhelpisappreciated.
OKJonathan,thatis:
publicfunctiongetButtonHtml(Mage_Catalog_Model_Product$product)
{
if($product>getId()&&!$product>getIsComposite()){
$qtyBlock=Mage::app()>getLayout()
>getBlock('[Link]');
$qtyBlock>setProduct($product)//**LINE20**
>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'';
}

someexemplesforwhatIwanttoget:[Link]
[Link]
@Oliver:checkingyourresponse
magento add cart products

editedJun1'11at10:08

askedMay31'11at9:00
Newbie
21

pasteinthecontentsof/app/code/local/BD83/MassAddToCart/Helper/Data.phparoundline20sothatwe
canseesomecontextpleaseJonathanDay May31'11at9:15
thanksforquickresponse,thatisthecode:publicfunctiongetButtonHtml(Mage_Catalog_Model_Product
$product){if($product>getId()&&!$product>getIsComposite()){$qtyBlock=Mage::app()>getLayout()
>getBlock('[Link]')$qtyBlock>setProduct($product)
>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''}
Newbie May31'11at9:25
pleaseedityourthequestionwiththecodeandformatitsothatit'sreadable:)andmarkwhichisline20.
thx JonathanDay May31'11at9:40
I'[Link],
StackOverflowisn'taforumifyouhaveanewquestion,[Link]
moreinformationinyourquestion,[Link]
answered,youcanleavethemacomment.WillMay31'11at15:17
ok,thankuWill. Newbie Jun1'11at10:10

2Answers

stillsearching?Foundthisone:
[Link]
Seemstoworkincurrentversions,thoughIhaven'[Link],atleastfuture
searcherswillknowwheretofindit!
/EDIT*/
Well,to"notbeconsideredapooranswer",[Link]
thecodeismywork,credstoUniMan,NexusRexandtheMagentoForumguys:)
[Link]
"Company"withthename"Module".
First,implementthehelperinapp/code/local/Company/Module/helper/[Link]:
<?php
classCompany_Module_Helper_MultipleextendsMage_Core_Helper_Url
{
/**
*Returnurltoaddmultipleitemstothecart
*@returnurl
*/
publicfunctiongetAddToCartUrl()
{
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,[Link]
app/design/base/default/templates/catalog/[Link]
app/design/default/default/templates/catalog/[Link],oncetheextension
isnolongerwanted,you/[Link]
[Link]:
After
<?phpecho$this>getToolbarHtml();?>

add
<formaction="<?phpecho$this>helper('Module/multiple')>getAddToCartUrl()?>"
method="post"id="product_addtocart_form">
<buttonclass="formbutton"onclick="[Link]()"><span><?phpecho
$this>__('AddItemstoCart')?></span></button>

(Thiswillopentheformallfollowingitemswilladdinputboxesforquantity,soyoucanputall
[Link],too.)
Scrollingdown,youwillfindtheareawherenormallythe"AddToCart"buttonisgenerated:
<?phpif($_product>isSaleable()):?>

Replacethecontentoftheifblockwith:
<fieldsetclass="addtocartbox">
<inputtype="hidden"name="products[]"value="<?phpecho
$_product>getId()?>"/>
<legend><?phpecho$this>__('AddItemstoCart')?></legend>
<spanclass="qtybox"><labelfor="qty<?phpecho$_product>getId()
?>"><?phpecho$this>__('Qty')?>:</label>
<inputname="qty<?phpecho$_product>getId()?>"type="text"
class="inputtextqty"id="qty<?phpecho$_product>getId()?>"maxlength="12"value=""/>
</span>
</fieldset>

[Link],insertafter
<?phpecho$this>getToolbarHtml()?>

atthebottom:
<buttonclass="formbutton"onclick="[Link]()"><span><?phpecho
$this>__('AddItemstoCart')?></span></button>
</form>

Whatyoudohereis:generateasecond"AddTocart"Button,identicalwiththeoneontop
closetheform
Whenanitemistaddedtothecart,normallyMagentowillcalltheCheckout_CartController.We
havetomodifythisoneinordertoaddnotjustone,butallitemstothecartinthedeserved
quantity.
Therefore,addthefileapp/code/local/Company/Module/controllers/Checkout/[Link]
andfillinthis:
>require_once'Mage/Checkout/controllers/[Link]';
>
>classCompany_Module_Checkout_CartControllerextends
>Mage_Checkout_CartController{
>publicfunctionaddmultipleAction()
>{
>$productIds=$this>getRequest()>getParam('products');
>if(!is_array($productIds)){
>$this>_goBack();
>return;
>}
>
>foreach($productIdsas$productId){
>try{
>$qty=$this>getRequest()>getParam('qty'.$productId,0);
>if($qty<=0)continue;//nothingtoadd
>
>$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>__('%swassuccessfullyaddedtoyourshoppingcart.',
$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>__('Cannotadditemtoshoppingcart'));
>}
>}
>$this>_goBack();

>}}

WeareoverridingtheexistingMageCoreclasswithourown,resultingintheuseofourcontroller
forthispurpose.
Youwillalsohavetoaddthemodule'[Link]
app/code/local/Company/Module/etc/[Link]:
<?xmlversion="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>

Whatthisdoes:replacescalltocartcontrollerwithcalltoownmultiaddcontrollerregisters
helperappliesroutertofrontend
Pleasetellmeifmoredocumentationonthisisneeded.
editedSep5'12at18:15

answeredSep5'12at12:51
simonthesorcerer
409

Lonelinkisconsideredapooranswersinceitismeaninglessbyitselfandtargetresourceisnotguaranteed
[Link].j0k Sep5
'12at13:06

There'saneasierwaytodothiswithjQuery/[Link] <li>
[Link] dataproductid whichcontainthenumericIDofeach
[Link],I'msureyouknowthatyoucanaddmultipleproductstoashoppingcartusinga
URLsuchas [Link]
(Replacethenumbers1,2and3withyourownproductID's.)
KnowingthisifyouhaveapageofproductswecanusejQuery/JavaScripttogenerateaURL
thatgetsalltheproductID'sforeachproductonthepage,andplacethemaccordinglywithina
URLliketheabove.
Toaccomplishthis,first,makesureyouhavejQueryaddedtoyoursite:
<scriptsrc="[Link]
<scriptsrc="[Link]

Now,addthefollowingscripttherearenotestoletyouknowwhateachvariableandfunction
does:
<script>
$(document).ready(function(){
//FunctiontogetallproductID's,&createaURLthatwilladdalltheitems
functiongenerateUrl(){
//thevariable'firstItem'willfindthefirstProductIDinanlitag
varfirstItem=$("li").first().attr("dataproductid");
//thevariable'otherItem'willearchallotherli's,andgrabtheirproductID's

varotherItem=$('li').nextAll().map(function(){return$(this).attr('dataproduct
id');}).get();
//thenewURLcreatestheURLthataddstheproductstothecart;replacethesiteURL
withyourown.
varnewUrl='[Link]
'&related_product='+otherItem;
//thisseeksalinkwiththeIDof"productlink",thenwilladdtheURLgeneratedfrom
newURLtothehreftag
$('#productlink').attr("href",newUrl);
}
//startfunction!
generateUrl();
});
</script>

Now,createalinkwiththeidofproductlink.
<ahref=""id="productlink">AddAllItemsToCart</a>

That'sit!
answeredMay30'13at2:31
David
1

protectedbyCommunity Aug11'14at16:53
[Link],postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestions instead?

You might also like