I want to set custom price programmatically to the product Magento 2
Try the following code to update price
foreach ($products_array as $value) {
$params['qty'] = 1;//product quantity
$_product = $this->productRepository->getById($value);
$_product->setPrice(153);
$_product->setBasePrice(153);
$quote->addProduct($_product,$params);
}
You can achieve this with the observer.
First create events.xml file in folder ‘test/Hello/etc/frontend’ and use event ‘checkout_cart_product_add_after’.
<?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="test\Hello\Observer\CustomPrice" />
</event>
</config>
Now create CustomPrice.php file in Observer folder.
<?php
/**
* test Hello CustomPrice Observer
*
* @category test
* @package test_Hello
* @author test
*
*/
namespace test\Hello\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class CustomPrice implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer) {
$reqeustParams = $this->_request->getParams();
$customproducttype = $reqeustParams['custom_product_type'];
if($customproducttype == "custom_product_type"){
$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);
}
}
}
You can pass some custom parameter while adding the product to the cart.
$params['qty'] = 1;//product quantity
$params['custom_product_type'] = "test" ;//product price
$_product = $this->productRepository->getById($value);