I am trying to set the custom price of product to cart using Magento2 but unable to do that. For that I have created a module TW - as namespace Cart- as Module name . So under TW/Cart I have created 2 folders etc and Observer. Below is the code in respective folders. Do i need to register this module by putting registration.php file under this module ? Please help me what am I doing wrong?
Code for etc/frontend/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="cart_observer_customprice" instance="TW\Cart\Observer\CustomPrice" />
</event>
</config>
Code for Observer/CustomPrice.php
namespace TW\Cart\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Psr\Log\LoggerInterface;
class CustomPrice implements ObserverInterface
{
protected $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$item = $observer->getEvent()->getData('quote_item');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = 120; //set your price here
$this->logger->debug("Hello I am here", [
'price' => $price,
]);
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}
}