Magento 2 – Set Custom Price When Adding Product to Cart

event-observermagento2price

I see some answers about set custom price in product when add to cart.

But, I can't still solve my issue. I used observer for that to set custom price.

But, it's not working.

Can anyone please help me to solve it?

My code :

public function execute(\Magento\Framework\Event\Observer $observer) {
    $item = $observer->getEvent()->getData('quote_item');
    $product = $observer->getEvent()->getData('product');
    $itemProId = $item->getProduct()->getId();
    $custom_price = $product->getPrice() + 10;
    $item->setCustomPrice($custom_price);
    $item->setOriginalCustomPrice($custom_price);
    $item->getProduct()->setIsSuperMode(true);
}

Best Answer

You doesn't return anything in your observer code. So, it's not update product price.

Make sure that you use checkout_cart_product_add_after event.

=> 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 name="checkout_cart_product_add_after">
        <observer name="custom_price_cart_add_after" instance="VendorName\ModuleName\Observer\CustomPriceCartAddAfter" />
    </event>
</config>

=> CustomPriceCartAddAfter.php (Observer File) :

Add return $this object at the end of your code inside

public function execute(\Magento\Framework\Event\Observer $observer) {
    $item = $observer->getEvent()->getData('quote_item');
    $product = $observer->getEvent()->getData('product');
    $itemProId = $item->getProduct()->getId();
    $custom_price = $product->getPrice() + 10;
    $item->setCustomPrice($custom_price);
    $item->setOriginalCustomPrice($custom_price);
    $item->getProduct()->setIsSuperMode(true);
    return $this;
}
Related Topic