skip to Main Content

I am currently trying to add a product to my cart useing this code.

  $quote = $this->_session->getQuote();
  $quote->addProduct($product);
  $this->_cartRepository->save($quote);

When I do this in a new session, the price of the product and the subtotal show as 0.00, but in the summary the Subtotal and Order Total are correct.
After editing the product quantity, the prices all function as they should.

I have tried to use $quote->collectTotals();, but this gives no visible changes.

How can I update cart so that the price of the product shows when I open the cart page?

2

Answers


  1. Try with this code:

    use MagentoCheckoutModelCart as Quote;
    
    class Add {   
    
       protected $quote = null;
    
       public function __construct( Quote $quote){
            $this->quote = $quote;            
       }
    
       public function test(MagentoCatalogModelProduct $product){
            $options = ['qty'=> 1];          
            $this->quote->addProduct($product, $options);
            //OR  $this->quote->addProductsByIds([$product->getId()]);
    
            $this->quote->save();
       }
    }
    

    Or

       public function test(MagentoCatalogModelProduct $product){
            $quote = $this->_objectManager->get(MagentoCheckoutModelCart:class);
            $options = ['qty'=> 1];          
            $quote->addProduct($product, $options);
            //OR  $quote->addProductsByIds([$product->getId()]);
    
            $quote->save();
       }
    
    Login or Signup to reply.
  2. You need to reload the quote from a DB to have all collectedTotals flags empty there.

    /** @var MagentoQuoteApiCartRepositoryInterface $quoteRepository */
    $quoteRepository->get($quoteId);
    $quote->addProduct($product, $request);
    $quote->collectTotals()->save();
    

    See MagentoQuoteModelQuote::collectTotals and MagentoQuoteModelQuoteAddressTotalSubtotal::collect

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search