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.

 * 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) {
        $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
                    $customer= $this->_customerRepositoryInterface->getById($customer_new->getId());

                    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);    


            $this->messageManager->addSuccessMessage(__("Please check your inbox..."));


When i use this code i got the error like "We found an invalid request for adding product to quote."

Please help me....Thanks!!!


5 Answers 5


Try the following code to update price

    foreach ($products_array as $value) {
        $params['qty'] = 1;//product quantity
        $_product = $this->productRepository->getById($value);
  • Wow!!! it is working.. Thanks. you are genius man...!!! Mar 6, 2018 at 7:28
  • 1
    Hey @Priyank , Your code was really working and it set the price to zero.When i go to the customer cart page the summary section not updated to my custom price. please see this screenshot.. nimb.ws/1yQLUG Mar 19, 2018 at 9:07
  • 1
    I can set the price as 0 but on cart page when product summary load at that time I can see the origin price so how can i solve that issue?
    – Kushal
    Mar 20, 2018 at 5:39

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" />

Now create CustomPrice.php file in Observer folder.

         * 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


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);  
  • how to set custom tax price for product? May 14, 2019 at 11:09
  • This one working on the first add to cart but when again adding the add to cart, the product in cart revert back to the base price. Why? Kindly help me Sep 18, 2019 at 18:53

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);

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');


You can achieve this with Event and Observer. There are following steps:

  • Step 1: Create Simple Extension
  • Step 2: Declaration of Module
  • Step 3: Registration of Module
  • Step 4: Activate the Module
  • Step 5: Declare event
  • Step 6: Create Observer for Custom Price

We need to catch the event - checkout_cart_product_add_after in step 5. In the Observer, write the code to set the custom price.


You need to add $item->save(); after $item->getProduct()->setIsSuperMode(true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.