Magento – Set custom price of product when adding to cart code not working

event-observermagento2

I have write module for set custom price of product when adding to cart but my code not working.

     namespace Navin\Testcart\Observer;

        use Magento\Framework\Event\ObserverInterface;
        use Magento\Framework\App\RequestInterface;

        class CustomPrice implements ObserverInterface
        {
            public function invoke(\Magento\Framework\Event\Observer $observer) {
                //echo "test";exit();
                 $item=$observer->getEvent()->getData('quote_item');
                 $product=$observer->getEvent()->getData('product');
                $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
                // Load the custom price
                $price = $product->getPrice()+10; // 10 is custom price. It will increase in product price.
                // Set the custom price
                $item->setCustomPrice($price);
                $item->setOriginalCustomPrice($price);
                // Enable super mode on the product.
                $item->getProduct()->setIsSuperMode(true);
            }

        }
  

Help for resolve my issue.

Best Answer

Please use this even checkout_cart_product_add_after, and also I suggest you that

ObserverInterface has only one method which is execute, so write your code in this method.

And do not use parent Item because while you are adding to cart any item then price depend upon child item so the best way is to use directly that item object that you are getting. So best practice is to use that item itself.

And also return $this object at the end of your code inside execute method.

For eg: namespace Navin\Testcart\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class CustomPrice implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer) {

        $item=$observer->getEvent()->getData('quote_item');
        $product=$observer->getEvent()->getData('product');
        // here i am using item's product final price
        $price = $item->getProduct()->getFinalPrice()+10; // 10 is custom price. It will increase in product price.
        // Set the custom price
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        // Enable super mode on the product.
        $item->getProduct()->setIsSuperMode(true);
        return $this;
    }

}

Hope this will help you. :)

Related Topic