I want to set custom price programmatically to the product Magento 2
-
02-01-2021 - |
Pergunta
I want to set the custom price for the product programmatically.In my current code , the customer create programmatically and set the products to the newly created customer.But i want set all product with the custom price. My code is working properly with the default product price but i want set the products with the custom price.Please see my code.
<?php
/**
*
* Copyright © 2015 Detailcommerce. All rights reserved.
*/
namespace Mp\Accountmanager\Controller\Accountmanager;
class Amsave extends \Magento\Framework\App\Action\Action
{
protected $_messageManager;
protected $cart;
protected $product;
protected $resultPageFactory;
protected $customerRepositoryInterface;
protected $quoteModel;
protected $productRepository;
protected $cartManagementInterface;
protected $cartRepositoryInterface;
protected $storeManager;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
\Magento\Quote\Model\Quote $quoteModel,
\Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
\Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Model\Product $product,
\Magento\Checkout\Model\Cart $cart) {
parent::__construct($context);
$this->_messageManager = $messageManager;
$this->storeManager = $storeManager;
$this->resultPageFactory = $resultPageFactory;
$this->cart = $cart;
$this->_customerRepositoryInterface = $customerRepositoryInterface;
$this->cartManagementInterface = $cartManagementInterface;
$this->quoteModel = $quoteModel;
$this->cartRepositoryInterface = $cartRepositoryInterface;
$this->productRepository = $productRepository;
$this->product = $product;
}
public function execute()
{
$post = $this->getRequest()->getParams();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$state = $objectManager->get('\Magento\Framework\App\State');
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
$websiteId = $storeManager->getWebsite()->getWebsiteId();
$store = $storeManager->getStore(); // Get Store ID
$storeId = $store->getStoreId();
$customer = $objectManager->create('Mp\Accountmanager\Model\Accountmanager');
$cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
$quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
$quote->setStoreId($this->storeManager->getStore()->getId());
$customer= $this->_customerRepositoryInterface->getById($customer_new->getId());
$quote->setCurrency();
$quote->assignCustomer($customer);
if($customerSession->getProcuctIdsSm() != NULL)
{
$products_array = $customerSession->getProcuctIdsSm();
$products_array = explode(',', $products_array);
}
$qty = 1;
$params = array();
foreach ($products_array as $value)
{
$params['qty'] = 1;//product quantity
$params['price'] = 153;//product price
$_product = $this->productRepository->getById($value);
$quote->addProduct($_product,$params);
}
$quote->collectTotals()->save();
$this->messageManager->addSuccessMessage(__("Please check your inbox..."));
$this->_redirect('checkout/cart');
}
}
When i use this code i got the error like "We found an invalid request for adding product to quote."
Please help me....Thanks!!!
Solução
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);
}
Outras dicas
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);
This Worked for me.
In a controller:
$price = rand(0,1000);
$this->product->setData('custom_overwrite_price', $price);
$params = [
'form_key' => $this->formKey->getFormKey(),
'qty' => 1
];
$this->cart->addProduct($this->product, $params);
$this->cart->save();
In checkout_cart_product_add_after
public function execute(\Magento\Framework\Event\Observer $observer) {
$item = $observer->getEvent()->getData('quote_item');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = $item->getProduct()->getData('custom_overwrite_price');
if($price){
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}
}
You need to add $item->save(); after $item->getProduct()->setIsSuperMode(true);