2

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???

7
  • is this event firing?
    – Amit Bera
    Jul 26, 2017 at 17:25
  • Yes, it is firing because product price is $22.95 and I have added $40, so price price is showing $62.95
    – Aveek
    Jul 27, 2017 at 5:38
  • @AmitBera do you have any idea how to overcome the problem?
    – Aveek
    Jul 27, 2017 at 6:10
  • any Update on this...? Nov 17, 2017 at 12:41
  • any update on this? Feb 21, 2018 at 8:55

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.