Tamanna
Tamanna

Reputation: 93

How to check if a Magento product is already added in cart or not?

I want to show popup when a product is first added to cart in Magento and don't want to show a popup if the product was added again or updated.In short, I want to know product which is going to be added in the cart is First occurence or not?

Upvotes: 9

Views: 15949

Answers (2)

Drew Hunter
Drew Hunter

Reputation: 10114

The answer largely depends on how you want to deal with parent/child type products (if you need to).

If you are only dealing only with simple products or you have parent/child type products and you need to test for child id's then:

$productId = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote();
if (! $quote->hasProductId($productId)) {
    // Product is not in the shopping cart so 
    // go head and show the popup.
}

Alternatively, if you are dealing with parent/child type products and you only want to test for the parent id then:

$productId = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote();

$foundInCart = false;
foreach($quote->getAllVisibleItems() as $item) {
    if ($item->getData('product_id') == $productId) {
        $foundInCart = true;
        break;
    }
}

EDIT

The question was asked in a comment as to why setting a registry value in controller_action_predispatch_checkout_cart_add is not available to retrieve in cart.phtml.

Essentially registry value are only available through the life of a single request - you are posting to checkout/cart/add and then being redirected to checkout/cart/index - so your registry values are lost.

If you would like to persist a value across these then you can use the session instead:

In your observer:

Mage::getSingleton('core/session')->setData('your_var', 'your_value');

To retrieve the value

$yourVar = Mage::getSingleton('core/session')->getData('your_var', true);

The true flag being passed to getData will remove the value from the session for you.

Upvotes: 15

MagePsycho
MagePsycho

Reputation: 2004

In order check if the product is already in cart or not, you can simply use the following code:

$productId = $_product->getId(); //or however you want to get product id
$quote = Mage::getSingleton('checkout/session')->getQuote();
$items = $quote->getAllVisibleItems();
$isProductInCart = false;
foreach($items as $_item) {
    if($_item->getProductId() == $productId){
        $isProductInCart = true;
        break;
    }
}
var_dump($isProductInCart);

Hope this helps!

Upvotes: 0

Related Questions