Magento – Add product to cart with different price using observer

cartevent-observerpriceproductshopping-cart

I currently have an observer which watches for when a product is added to the shopping cart (checkout_cart_product_add_after) and applies a custom price from the product view page. This works fine but I need for it to add a separate version of the same product to the cart if the price is different from any of the current ones. E.g. so the user can buy 1x $400 item, 2x $300 item.

Can this be done ? Currently using a simple product as nothing varies other than the price.

Here is my observer function

public function applyCustomPrice($observer)
{

    $item = $observer->getQuoteItem();

    if ($item->getParentItem()) {
        $item = $item->getParentItem();
    }

    $product = $observer->getProduct();
    $max = $product->getMaxprice();
    if($max) {
        $max = $max * 1;
    } else {
        $max = 500;
    }

    $new_price = Mage::app()->getRequest()->getPost('priceInput');

    if($new_price > $max) {
        $item->getQuote()->removeItem($item->getId());
        $message = 'You must enter a value lower than $'.$max;

        //todo: could try _dataSaveAllowed

        Mage::throwException($message);
        return;
    }

    if(!is_null($new_price) && $this->isCurrency($new_price)) {
        $item->setCustomPrice($new_price);
        $item->setOriginalCustomPrice($new_price);
        $item->getProduct()->setIsSuperMode(true);
    }
}

function isCurrency($number)
{
    return preg_match("/^[0-9]+(?:\.[0-9]{1,2})?$/", $number);
}

Best Answer

This is not quite answering your question, but have you explored using sales rules instead of a coded solution? Go to the magento backend, click through to Promotions -> Shopping Cart Price Rules.