Sie sind auf Seite 1von 5

signup

login

tour

help

stackoverflowcareers

Signup

StackOverflowisacommunityof4.7millionprogrammers,justlikeyou,helpingeachother.Jointhem,itonlytakesaminute:

AddmultipleproductstocartMagento

Itrytousethathttp://sourceforge.net/projects/massaddtocart/
ItisexactlywhatIwant,butitshowsthiserror:
Fatalerror:CalltoamemberfunctionsetProduct()onanonobjectin
[...]/app/code/local/BD83/MassAddToCart/Helper/Data.phponline20

Iwanttotoaddmultiplesimpleproductswithdifferentqtytocartbyoneclick.thisoptiondoesnotexistinMagento.
Anyhelpisappreciated.
OKJonathan,thatis:
publicfunctiongetButtonHtml(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)//**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:http://www.dickblick.com/products/winsorandnewtonartistsacrylics/
http://www.polymexint.com/nouvellemontanablackblk400ml.html
@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('bd83.massaddtocart.catalog.product.list.item.button')$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'vemergedyourtwoaccountstogether.PleasereadthisFaqentryaboutcookiebasedaccounts.Also,
StackOverflowisn'taforumifyouhaveanewquestion,pleaseaskanewquestion.Ifyouwanttoinclude
moreinformationinyourquestion,pleaseeditit.Ifyouwanttointeractwithoneofthepeoplewhohas
answered,youcanleavethemacomment.WillMay31'11at15:17
ok,thankuWill. Newbie Jun1'11at10:10

2Answers

stillsearching?Foundthisone:
http://www.magentocommerce.com/boards/viewthread/9797
Seemstoworkincurrentversions,thoughIhaven'ttestedityet.Ifyousolvedit,atleastfuture
searcherswillknowwheretofindit!
/EDIT*/
Well,to"notbeconsideredapooranswer",thishowyoushouldimplementthesolution.Noneof
thecodeismywork,credstoUniMan,NexusRexandtheMagentoForumguys:)
Thecodeiswelldocumented.ItcreatesafullworthyMagentoextensioninthenamespace
"Company"withthename"Module".
First,implementthehelperinapp/code/local/Company/Module/helper/Data.php:
<?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,youwillneedtodosometemplatechanges.Copythefile
app/design/base/default/templates/catalog/list.phtmlto
app/design/default/default/templates/catalog/list.phtml.Thismakessurethat,oncetheextension
isnolongerwanted,you/yourclientcangobacktothenormallistviewwithoutcoding.Modifythe
newlist.phtmlfileasfollows:
After
<?phpecho$this>getToolbarHtml();?>

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

(Thiswillopentheformallfollowingitemswilladdinputboxesforquantity,soyoucanputall
itemsinthecartusingonesolebutton.Thisisputhere,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>

Thisistheinputfieldforthequantity.Toclosethetag,insertafter
<?phpecho$this>getToolbarHtml()?>

atthebottom:
<buttonclass="formbutton"onclick="productAddToCartForm.submit()"><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/CartController.php
andfillinthis:
>require_once'Mage/Checkout/controllers/CartController.php';
>
>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'sconfig.xmlasusualin
app/code/local/Company/Module/etc/config.xml:
<?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
tobealiveinthefuture.Pleasetrytoincludeatleastsummaryofinformationyouarelinkingto.j0k Sep5
'12at13:06

There'saneasierwaytodothiswithjQuery/Javascript.Allproductsonthepagearein <li>
tags.Thesetagshaveanattributecalled dataproductid whichcontainthenumericIDofeach
product.Also,I'msureyouknowthatyoucanaddmultipleproductstoashoppingcartusinga
URLsuchas http://www.yoursite.com/checkout/cart/add?product=1&related_product=2,3
(Replacethenumbers1,2and3withyourownproductID's.)
KnowingthisifyouhaveapageofproductswecanusejQuery/JavaScripttogenerateaURL
thatgetsalltheproductID'sforeachproductonthepage,andplacethemaccordinglywithina
URLliketheabove.
Toaccomplishthis,first,makesureyouhavejQueryaddedtoyoursite:
<scriptsrc="http://code.jquery.com/jquery1.10.0.min.js"></script>
<scriptsrc="http://code.jquery.com/jquerymigrate1.2.1.min.js"></script>

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='http://shop.yoursite.com/checkout/cart/add?product='+firstItem+
'&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
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityanswers,postingananswernowrequires10reputationonthissite.
Wouldyouliketoansweroneoftheseunansweredquestions instead?

Das könnte Ihnen auch gefallen