farjam
farjam

Reputation: 2289

Add exactly 1 product to cart programmatically in Magento

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

Upvotes: 0

Views: 949

Answers (1)

PixieMedia
PixieMedia

Reputation: 1548

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); }
}

Upvotes: 1

Related Questions