4

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!!!

3

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); 
    }                   
  • Wow!!! it is working.. Thanks. you are genius man...!!! – Sunny Rahevar Mar 6 '18 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 – Sunny Rahevar Mar 19 '18 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 '18 at 5:39
3

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);  
  • how to set custom tax price for product? – jafar pinjar May 14 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 – Kowsigan Atsayam Sep 18 at 18:53
-1

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.