Magento 2: How to set a custom price of a product?
-
11-10-2020 - |
Question
In Magento 2, I need to set the custom price of a product pro-grammatically when admin creates an order from backend.
For example, in this page
'www.site.com/admin/sales/order_create/index/key/a0f4c...
when an admin click's 'Add Selected Product(s) to Order' (after clicking 'add products'), I want to compute prices of that selected products through some formula then assign these prices as a custom price to that products.
So what I really need is a piece of code by which Magento assigns custom price to product.
Solution
Create events.xml file at app/code/YourNamespace/YourModule/etc/frontend
<?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="custompricemodule" instance="YourNamespace\YourModule\Observer\CustomPrice" />
</event>
</config>
Create CustomPrice.php file at app/code/YourNamespace/YourModule/Observer
<?php
namespace YourNamespace\YourModule\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');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = 100; //set your price here
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}
}
Hope this will help you :)
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange