0
votes

Using Magento 1.8.1, on the checkout page, I'm trying to add a product to the cart in the code. Here is the code I'm using:

    $totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
    $subtotal = $totals["subtotal"]->getValue();
    $free_samples_prod_id = 1285;
    if ( $subtotal >= 50 ) {
        $this->addProduct($free_samples_prod_id, 1);
    }
    else{
        $cartHelper = Mage::helper('checkout/cart');
        $items = $cartHelper->getCart()->getItems();
        foreach ($items as $item) {
            if ($item->getProduct()->getId() == $free_samples_prod_id) {
                $itemId = $item->getItemId();
                $cartHelper->getCart()->removeItem($itemId)->save();
                break;
            }
        }
    }

The code is in: app\code\core\Mage\Checkout\Model\Cart.php under public function init()

The product does get added sucessfully, however, everytime somebody visits their cart page, the quantity increases by one. How can I modify that code so the quantity is always 1?

Thank you

1
Where are you inserting this code? Something is causing it to run each page load it seems, so you might want to address that.Axel
I've added it under public function init() of app\code\core\Mage\Checkout\Model\Cart.phpfarjam
Why are you introducing foreign code into core Models? You should be either extending the core through an extension, or overriding the files using the app/code/local/Mage folder. And putting code under the init method means it's going to run each time the cart is loaded.Axel

1 Answers

1
votes

Axel makes a very good point, but to answer your immediate question, why not test for the product's presence before you add it

$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;

if ( $subtotal >= 50 ) {

    $alreadyAdded = false;
       foreach ($items as $item) {
           if($item->getId() == $free_samples_prod_id) { $alreadyAdded = true; break; }
       }
    if(!$alreadyAdded) { $this->addProduct($free_samples_prod_id, 1); }
}