9

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

4

2 回答 2

15

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

如果您只处理简单的产品或者您有父/子类型的产品并且您需要测试子 ID,那么:

$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.
}

或者,如果您正在处理父/子类型的产品并且您只想测试父 ID,那么:

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

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

编辑

在评论中询问了为什么controller_action_predispatch_checkout_cart_add无法在 cart.phtml 中检索设置注册表值的问题。

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

如果您想在这些之间保留一个值,那么您可以改用会话:

在你的观察者中:

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

检索值

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

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

于 2012-07-26T15:13:06.873 回答
0

为了检查产品是否已经在购物车中,您可以简单地使用以下代码:

$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);

希望这可以帮助!

于 2012-07-26T13:36:08.873 回答