Magento – Magento 2 – custom price can not add to subtotal and grand total after add to cart

addtocartcartmagento2mini-cart

I want to add custom price for bundle products after adding to cart. I have used "checkout_cart_product_add_after" observer to do so. But it is adding custom price to product price, not in sub total and grand total.
Following is my code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <!-- Event for add to cart -->
    <event name="checkout_cart_product_add_after">
        <observer name="customprice_observer_set_price_for_item_add" instance="Custom\Shop\Model\Observer\SetPriceForItem"/>
    </event>
</config>

Observer class:

namespace Custom\Shop\Model\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\Product\Type;

class SetPriceForItem implements ObserverInterface
{
     public function execute(Observer $observer)
     {
        $item = $observer->getEvent()->getQuoteItem();
        if ($item->getProduct()->getTypeId() == Type::TYPE_BUNDLE) {
            foreach ($item->getQuote()->getAllItems() as $bundleitems) {
                if ($bundleitems->getProduct()->getTypeId() == Type::TYPE_BUNDLE) {
                    $bundle_price = $bundleitems->getProduct()->getFinalPrice();
                    $fee = $bundleitems->getProduct()->getBuildInFee();
                    $final_price = $bundle_price + $fee;
                    $bundleitems->setCustomPrice($final_price);
                    $bundleitems->setOriginalCustomPrice($final_price);
                }
            }

            $item->getProduct()->setIsSuperMode(true);
        }
        return $this;
     }
}

Is there anyone who can help me? Price is not adding to subtotal and
grand total.

Following is the cart item, subtotal and grand total.

enter image description here

Any help???

Best Answer

I had smiliar problem, but in my case, subtotal was 0 after adding the product to the cart. Try with this:

$cart->setTotalsCollectedFlag(false); $cart->getShippingAddress()->setCollectShippingRates(true); $cart->collectTotals(); $this->cartRepository->save($cart);

The missing line was $cart->getShippingAddress()->setCollectShippingRates(true);. You can find same solution in \Magento\Checkout\Model\Cart::save() method.