2

I have used below code to delete quote item from the cart and add it again in my controller

 $referenceProductId = $this->getRequest()->getPost('product_id')
 $customPrice = 100;
 $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product_id' => $referenceProductId, //product Id
                'qty'   => 1 //quantity of product                
        );  
 $cartItems = $this->cart->getQuote()->getAllItems();
        if(empty($cartItems)){
            $status = $this->addProductCart($referenceProductId,$customPrice,$params);

        }else{
            foreach ($cartItems as $item) {
                $itemId = $item->getItemId();
                if ($referenceProductId == $item->getProductId()) {
                    $this->cart->removeItem($itemId);
                    $status = $this->addProductCart($referenceProductId,$customPrice,$params);
                    //return;
                }
                 else{                      
                    $status = $this->addProductCart($referenceProductId,$customPrice,$params);
                }  
            }
        }   

  public function addProductCart($referenceProductId,$customPrice,$params)
{

 try{
       $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product_id' => $referenceProductId, //product Id
                'qty'   => 1 //quantity of product                
        );  
        $_product = $this->product->create()->load($referenceProductId);
        $this->cart->addProduct($_product, $params);
        $productItem = $this->getProductQuote($_product);
        $productItem->setCustomPrice($customPrice);
        $productItem->setOriginalCustomPrice($customPrice);
        //Enable super mode on the product.
        $productItem->getProduct()->setIsSuperMode(true);
        $this->cart->save();
        $quote = $this->cart->getQuote();
        $quoteId = $quote->getId();
        $customerId = $this->getCustomerId();

        $status = 1;
    }catch (\Magento\Framework\Exception\LocalizedException $e) {
        $this->messageManager->addException($e,__('%1', $e->getMessage()));
        $status = 0;
    } catch (\Exception $e) {
        $this->messageManager->addException($e, __('error.'));
        $status = 0;
    }
    return $status;
}

public function getProductQuote($product){
     $quote = $this->checkoutSession->getQuote();       
     $cartItems = $quote->getItemByProduct($product);       
     return $cartItems;
}

In above code I am checking if same product adding again, removing the item from quote and inserting again.

But this is not working for me. Item Qty is always 1 but price is not affected

can anyone look into this please?

Your Answer

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

Browse other questions tagged or ask your own question.