updating subtotal when products added to cart

2019-09-08 09:02发布

问题:

I am currently adding products programatically to the cart, to create a 'free sample' aspect to my site.

Currently, all of these products are $0 and you can add a maximum of 15. Once you have 5 'free sample' products in the cart, I need to add $20 to the subtotal.

I know I can get the grandtotal using:

Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal();

But how do I access the subtotal and also add $20 to it?

I'm guessing I'll need to write an observer, as I'll need to check when products are added/removed from the cart in order to either add the $20 or not.

Has anyone done this before or could point me in the right direction of how I could do this?

Many thanks

Thanks

回答1:

I actually answered this question recently here is a basic idea of what needs to be done, let me know if you need more specific details: Add an observer which looks for this event 'sales_quote_add_item':

<events>
    <sales_quote_add_item>
        <observers>
            <priceupdate_observer>
                <type>singleton</type>
                <class>mymodule/observer</class>
                <method>updatePrice</method>
            </priceupdate_observer>
        </observers>
    </sales_quote_add_item>

The observer should have a method which does something like this:

public function updatePrice($observer) {
    $event = $observer->getEvent();
    $quote_item = $event->getQuoteItem();
    if(sample etc...) $new_price = <insert logic>
    $quote_item->setOriginalCustomPrice($new_price);
    $quote_item->save();
}


回答2:

you are getting this slightly wrong, total is calculated over item prices you have in quote and "total" is not just something that you can add or subtract from like you wish to.

for your current task i'd suggest you to create a shopping cart rule "add x get n for free"



标签: magento