Magento: Check if product is already in cart

Tweet about this on TwitterShare on LinkedInShare on Google+Share on FacebookEmail this to someone

This morning I was looking for some new and interesting articles and I found one titled Are You Giving Your Users Positive Feedback? In this article I’ve found one very simple and elegant solution of something that always bothered me while shopping online. As I’m impatient person I always have problems with clicking more than once on the add to cart button and few times I’ve purchased items in bigger quantity that I’ve intended. I’ve never seen a web shop, that offers this simple solution presented in the article I’ve read – adding message for items that are already in the shopping cart.

 grid view  mockup showing added to cart products

After short search for existing modules or extensions I’ve decided to see how this can be done in Magento and if it’s too difficult to implement. With little brainstorming in The Lab it turned out that task is not difficult at all and we’ve decided to share the code with you.

We’ve created small module containing only three files:

The first one is our module XML file and it’s located in app/etc/modules. The filename we choose is CeckosLab_SmartView.xml. The file contains following code:

<?xml version="1.0"?>

	
		
			true
			local
		
	

The second one is app/code/local/CeckosLab/SmartView/etc/config.xml In our module this file contains module information and helper’s class that we’re using. The code is shown below:

<?xml version="1.0"?>

	
		
			1.0.0
		
	
	
		
			
				CeckosLab_SmartView_Helper
			
		
	

The third file is the heart of the module which in our case is just one simple helper. The file is locate in app/code/local/CeckosLab/SmartView/Helper and is named Data.php It contains constructor and two public methods. In the constructor we get the ID and the quantity of each product in the shopping cart and keep them as array in the member variable $_cartProductIds. The method isInCart() accepts as parameter object from class Mage_Catalog_Model_Product and returns true if the Product ID exists in the member variable $_cartProductIds. The function getQty() can be called to return the product’s quantity in your cart. The code of the helper is shown below:

class CeckosLab_SmartView_Helper_Data extends Mage_Core_Helper_Abstract
{
    protected $_cartProductIds;


    public function __construct() {
        $product_ids = array();
        $products = Mage::getSingleton('checkout/session')->getQuote()->getAllVisibleItems();
        foreach ($products as $_products){
            $product_ids [$_products->getProductId()] = $_products->getQty();
        }
        $this->_cartProductIds = $product_ids;
    }
    
    public function isInCart($product) {
        return array_key_exists($product->getId(), $this->_cartProductIds); 
    }
    
    public function getQty($product) {
        return  $this->_cartProductIds [$product->getId()]; 
    }

You can find our small module on GitHub and get it for free: https://github.com/ceckoslab/smart_view

After you have all three files in their proper locations all you need to do is to add few short lines of code. You need to do this in the template file app/design/frontend/yourpackage/yourtheme/template/catalog/product/list.phtml for both list and grid view. If the file does not exists in your theme copy it form the base theme and add the code there.

The first piece of code that needs to be added is call to our helper class.

    $_cartItemsHelper = Mage::helper('smartview');

The the second piece of code is repeated twice – once for the list view mode and once for the grid view mode. The code contains calls to both functions in our helper class. The code below is just an example usage – it will display short message right after the product name if the item is already in the cart.

<?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?>

<?php if ($_cartItemsHelper->isInCart($_product)): ?> <?php echo $_cartItemsHelper->getQty($_product); ?> item(s) already in your cart <?php endif; ?>

The expected results are shown on the screens below:

Well there is some room for improovements:

It will be great if we use custom DB query instead of Mage::getSingleton(‘checkout/session’)->getQuote()->getAllVisibleItems() with having in mind to fetch only the product ID and the quantity instead of fetching all the properties of Mage_Sales_Model_Quote_Item . In this way we will save some server resources and will decrease the load time.

All that’s left to do is to change the text and style it in order to blend in your design. Enjoy :)

References:

Tweet about this on TwitterShare on LinkedInShare on Google+Share on FacebookEmail this to someone

Ivan Nikolov

Ivan is our frontend developer. He graduated Computer Science in the University of Veliko Tarnovo. Before joining our company he worked as software engineer in ASIC Depot. There he gained his experience in programming languages as Verilog/System Verilog, verification using job specific tools as DVE and Verdi, creating test scenarious and technical documentation. He also have experience in web design - mostly small projects of personal interest. He is honest person and he hates being late!:) When not working he likes to chill out with friends. He also likes playing pool and long walks.

More Posts

  • Mitko

    Very well done and said indeed!

  • Swaroop

    Thank you soo much yar, your saved my time.

  • Pavan

    There is a mistake in your etc/modules/CeckosLab_SmartView.xml. Error is: tag has to be like this. But in the above code it is like . This returns me an error that Helper file not found. After modifying this, Everything works fine.

  • Pavan

    What is this?? the Capital letters in the “codePool” tags has turned into small letters??? Issue in ur wordpress. Check it out.

  • shan

    hi. i have added your code but in front-end on category page its shows error message as, Fatal error: Class ‘Mage_Smartview_Helper_Data’ not found in /app/Mage.php on line 547. may i know how to resolve this error ?

  • Naga

    Thank you for this article

  • Anurag

    error with etc/modules/CeckosLab_SmartView.xml . there is small p instead of capital P.