Magento – Magento2 Change bundle item price in cart

addtocartbundled-productcartmagento2

I would like to change the price of the bundle product items after its has been added to cart and recalculate the bundle product price and changing the bundle item price.

I was thinking of using the checkout_cart_product_add_after event but I am not sure how to modify the bundle item prices.

I have seen some of the answers here but they show how to modify the bundle product price not the bundle item prices

Shopping Cart Snapshot

Best Answer

So finally I was able to achieve this, first we need a events.xml

For my requirement I needed this event observer for both frontend and adminhtml so the events.xml was create at app/code/Foo/CustomPrice/etc/events.xml.

<?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="foo_customprice_observer_set_price_for_item_add" instance="Foo\CustomPrice\Model\Observer\SetPriceForItem"/>
    </event>
    <!-- Event for update add to cart -->
    <event name="checkout_cart_product_update_after">
        <observer name="foo_customprice_observer_set_price_for_item_update" instance="Foo\CustomPrice\Model\Observer\SetPriceForItem"/>
    </event>
</config>

After that need a observer at app/code/Foo/CustomPrice/Model/Observer/SetPriceForItem.php

<?php
namespace Foo\CustomPrice\Model\Observer;

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

class SetPriceForItem implements ObserverInterface
{
    /**
     * Add Special Price on add to cart.
     *
     * @param Observer $observer
     * @return SetPriceForItem
     *
     */
     public function execute(Observer $observer)
     {
        /** @var $item \Magento\Quote\Model\Quote\Item */
        $item = $observer->getEvent()->getQuoteItem();
        if ($item->getProduct()->getTypeId() == Type::TYPE_BUNDLE) {
            foreach ($item->getQuote()->getAllItems() as $bundleitems) {
                /** @var $bundleitems\Magento\Quote\Model\Quote\Item */
                //Skip the bundle product
                if ($bundleitems->getProduct()->getTypeId() == Type::TYPE_BUNDLE) {
                    continue;
                }
                $bundleitems->setCustomPrice(1.00);
                $bundleitems->setOriginalCustomPrice(1.00); 
                $bundleitems->getProduct()->setIsSuperMode(true);   

            }
            $item->getProduct()->setIsSuperMode(true);
        }
        return $this;
     }//end execute()
}
Related Topic