How to Display Notification When Adding Item to Cart in Magento 1.8/1.9

magento-1.8magento-1.9

I want to display a notification or message to the user; when he adds an item to the cart, which is limited to '1' item max. a message like : 'You can add 1 item maximum' . I did an observer to block the add but it shows me the error message in the log default magento. it's not pretty,I want to display it in the same page

My observer:

// Event: catalog_product_type_prepare_full_options    

public function limit_(Varient_Event_Observer $observer) {

    $quote = Mage::getSingleton('checkout/session')->getQuote();
    if($quote->getItemsCount()>=1){
        Mage::throwException('You can add 1 item maximum.');
    }

}

Best Answer

I'm assuming that throwing the exception prevents the actual item being added? If that's the case then you probably just want to do something like:

public function limit_(Varient_Event_Observer $observer) 
{
    $session = Mage::getSingleton('checkout/session');
    $quote = $session->getQuote();

    if($quote->getItemsCount()>=1){
        $message = 'You can add 1 item maximum.';
        $session->addError($message);          
        Mage::throwException($message);
    }
}

Assuming that your blocks on the frontend are all pretty vanilla, they should output the Mage messages on page load which will include this error message added to the session.

Just a note, that the logic you've got here will only allow a single item to be added to the cart. In its entirety.

If you sold Hats and Shirts, this would allow you to only purchase 1 hat or 1 shirt. Is this the functionality you want or do you want it to be more like 1 hat and 1 shirt or 1 hat and 0 shirt or 0 hat and 1 shirt?

If so, you will need to drill into the $quote->getItems() and validate that the item you're adding has not already been added to the quote.