1

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);
}

1 Answer 1

2

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;
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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