A custom price of the product when Magento 2 add product to cart by using Observe. In many cases, the clients are willing to allow add product to cart at a custom price. This operation already calculated price by Magento.
Magento calculates the lowest price from one of the base price, special price, tier price, or catalog rule price. Configurable products can set their own prices for child products and bundle products can apply a fixed price on the bundle. Then when adding the product to the cart its price can be affected by cart price rules too.
A pricing/repricing rule requires three sets of information during its setup:
Let’s you add your customized price explore two steps below!
Here we are using Dolphin as Vendor name and CustomPrice as the name of module. You can change this according to your Vendor and Module name
The first thing you need to do is to create an events.xml file in the folder app/code/Dolphin/CustomPrice/etc/frontend and use event checkout_cart_product_add_after which will be called after adding a product to the cart.
<?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="dolphin_customprice_checkout_cart_product_add_after" instance="Dolphin\CustomPrice\Observer\CartProductAddAfter"/> </event> </config>
Here you declare an observer named CartProductAddAfter that will handle the event checkout_cart_product_add_after which Magento dispatches every time a product’s added to the cart.
Know more About: Magento 2 Call for Price
Now we need to create an Observer as defined in the events.xml file
You have to create CartProductAddAfter.php file that overrides your price in the observer folder.
<?php namespace Dolphin\CustomPrice\Observer; use Magento\Framework\App\RequestInterface; class CartProductAddAfter implements \Magento\Framework\Event\ObserverInterface { public function execute( \Magento\Framework\Event\Observer $observer ) { $item = $observer->getEvent()->getData('quote_item'); $product = $item->getProduct(); $price = $product->getPrice(); $item = ( $item->getParentItem() ? $item->getParentItem() : $item ); if($price){ //add price login here. //$this->getConfigPrice(); get system config value for custom price. $mainPrice=$price + $this->getConfigPrice();//product price + custom price(this price get from system config.) $item->setCustomPrice($mainPrice);//set custom price $item->setOriginalCustomPrice($mainPrice);//set original custom price $item->getProduct()->setIsSuperMode(true); } } }
That’s it!
if you are facing any issues during implementation, use the comment section below!
Happy Coding!
Click one of our contacts below to chat on WhatsApp