如何检查购物车中是否已添加Magento产品? [英] How to check if a Magento product is already added in cart or not?

查看:75
本文介绍了如何检查购物车中是否已添加Magento产品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在将商品首次添加到Magento中的购物车时显示弹出窗口,而不希望再次添加或更新该商品时显示弹出窗口.简而言之,我想知道要添加的商品在购物车中是不是第一次出现?

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?

推荐答案

答案很大程度上取决于您要如何处理父子类型的产品(如果需要).

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

如果您仅处理简单产品,或者您拥有父母/孩子类型的产品,并且需要测试孩子的ID,则:

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

编辑

在评论中询问了该问题,为什么不能在cart.phtml中检索在controller_action_predispatch_checkout_cart_add中设置注册表值.

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.

基本上,注册表值仅在单个请求的生命周期内可用-您将其发布到checkout/cart/add,然后重定向到checkout/cart/index-因此,您的注册表值会丢失.

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:

在您的观察者中:

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

要获取值

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

传递给getData的true标志将为您从会话中删除该值.

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

这篇关于如何检查购物车中是否已添加Magento产品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆