I want to set a custom price of the product when adding to cart using an observer. For that, I added this code but it's not working

enter image description here

app\code\Webkul\Hello\Observer\CustomPrice.php

<?php
    /**
     * Webkul Hello CustomPrice Observer
     *
     * @category    Webkul
     * @package     Webkul_Hello
     * @author      Webkul Software Private Limited
     *
     */
    namespace Webkul\Hello\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;
        }
    }

app\code\Webkul\Hello\etc\frontend\checkout_cart_product_add_after.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="customprice" instance="Webkul\Hello\Observer\CustomPrice" />
    </event>
</config>
有帮助吗?

解决方案

It seems the problem is in your event file name,

Hoping that you didn't edit while asking question above,

The file name should be events.xml instead of checkout_cart_product_add_after.xml

Hope this helps :)

许可以下: CC-BY-SA归因
scroll top