How to set a custom price of a product when adding to cart using an observer in Magento 2?
-
21-02-2021 - |
Question
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
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>
Solution
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 :)
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange