Same as Magento 1 , it is possible to set the custom product price. We can use same event we used in magento 1. But file structures are different, so we need to use some structure to use event observer.
Let’s see the file structure
app/code/Webmull/Customprice/etc/
app/code/Webmull/Customprice/etc/frontend/
app/code/Webmull/Customprice/Observer/
1. We create the module configuration price in the following path app/code/Webmull/Customprice/etc/ with name module.xml
2. We are using events to set the custom price. So we need to create events.xml. There are 3 types of events.xml
1) app/code/Webmull/Customprice/etc/ (It is used for global event)
2) app/code/Webmull/Customprice/etc/frontend/ (It is used to execute frontend event)
3) app/code/Webmull/Customprice/etc/adminhtml/ (It is used to execute adminhtml event)
As we are overwriting the product price in cart so we create the events.xml in the path app/code/Webmull/Customprice/etc/frontend/
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd"> <event name="checkout_cart_product_add_after"> <observer name="customprice" instance="Webmull\Customcartprice\Observer\BindCustomprice" method="invoke" /> </event> </config> |
Here in observer tag
name =>name of the method
instance =>path to read the file
method =>Which method we need to read from file
3. Use the invoke method which we need to write in BindCustomprice.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace Webmull\Customcartprice\Observer; class BindCustomprice { public function invoke(\Magento\Framework\Event\Observer $observer) { $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); } } |
So, now when the module will be installed and the product will be added to cart price will be change.