简体   繁体   English

收集总计 magento2 后更新购物车项目价格

[英]Update cart item price after collect totals magento2

I'm trying to update cart item price depends on quote grand total.我正在尝试更新购物车商品价格取决于报价总额。 I've made an observer to change price before cart is saved.我已经让观察者在保存购物车之前更改价格。 My problem is that values for changed items are changed in wrong time.我的问题是更改项目的值在错误的时间更改。 Example:例子:

I have two items in cart #1 Item - $150, #2 Item - $10, when I change qty ot first item total of this item is set to $300 (it's ok), however price of #2 Item is changed to 0 (it's ok) but in database I still see price, base_price, row_total, base_row_total, price_incl_tax, base_price_incl_tax, row_total_incl_tax, base_row_incl_tax with $10 values.我在购物车中有两件商品 #1 商品 - 150 美元,#2 商品 - 10 美元,当我更改数量时,该商品的第一件商品总额设置为 300 美元(没关系),但是 #2 商品的价格更改为 0(这是好的)但在数据库中我仍然看到price, base_price, row_total, base_row_total, price_incl_tax, base_price_incl_tax, row_total_incl_tax, base_row_incl_tax值为 10 美元。 When I again change qty of #1 Item, #2 Item changes price to $10 but values in database are now set to 0. Where and how should I change price to have correct data in database?当我再次更改 #1 商品的数量时,#2 商品将价格更改为 10 美元,但数据库中的值现在设置为 0。我应该在哪里以及如何更改价格以在数据库中获得正确的数据? Here is my code:这是我的代码:

events.xml:事件.xml:

<event name="checkout_cart_save_before">
    <observer name="Vendor::save_cart” instance="Vendor\Observer\BeforeCartSaveObserver" shared="false"/>
</event>

Observer:观察员:

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $cart = $observer->getCart();

    $quote = $this->checkoutSession->getQuote();

    $quote->collectTotals();
    $quote->setTotalsCollectedFlag(false);

    foreach ($quote->getAllVisibleItems() as $item) {
        $product = $item->getProduct();
        if (!$product->getIsFree()) {
            continue;
        }

        $freeItem = $item;
        break;
    }

    if ($quote->getGrandTotal() > 240) {
        $item->setCustomPrice(0)
            ->setOriginalCustomPrice(0)
            ->getProduct()->setIsSuperMode(true);
    } else {
        $product = $freeItem->getProduct();
        $defaultProductPrice = $product->getPriceInfo()
            ->getPrice('regular_price')
            ->getAmount()
            ->getBaseAmount();
        $item->setConvertedPrice($defaultProductPrice)
            ->setCustomPrice($defaultProductPrice)
            ->setOriginalCustomPrice($defaultProductPrice);

        $item->setPrice($defaultProductPrice)->setBaseOriginalPrice($item->getProduct()->getPrice());
    }
        $item->calcRowTotal();

    return $this;
}

try remove $quote->setTotalsCollectedFlag(false);尝试删除 $quote->setTotalsCollectedFlag(false); or call $quote->collectTotals();或调用 $quote->collectTotals(); after you changed price.更改价格后。 I see it helped some people我看到它帮助了一些人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM