Pregunta

I'm trying to fully truncate the cart.

I've override getAllVisibleItems in the checkout \Magento\Quote\Model\Quote Model But I still can visit the cart page and see the empty table of it, and the product also still showing up in the mini-cart

Here is my code

private function truncateUserQuote()
{
   $this->removeAllItems()->save();
   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $cs = $objectManager->create('\Magento\Checkout\Model\Session');
   $cs->getQuote()->removeAllItems()->save();
}
¿Fue útil?

Solución

Im sorry to call such attention to this question but there's a TON wrong here. Hopefully, you will take some lessons away from this answer.

  • Don't use the Object Manager in your code
  • Don't get the quote from the session. But IF you insist, you should probably use $objectManager->get('class name') not $objectManager->create('class name'). Get ensures that you get a shared instance of the class. Create instantiates a new instance of the class.
  • Don't override getAllVisibleItems - not sure what your purpose is for that but you WILL make trouble for yourself. Plugins are immediately available for your use and are a MUCH better choice. Also, getAllVisible items doesnt account for the child products if the customer has grouped, bundle, or configurable products. It really only accounts for the visible line items.
  • DO get used to looking at the Interfaces and using the methods contained in the interfaces only. Interfaces are basically a set of promises to provide the functions you are using. Referencing functions from concrete PHP classes will render your functionality broken during some future upgrade.

Here is a working example. We don't reference the session or object manager and we use only methods available according to the service contract. Work this into your code and test it out.

<?php

class CartTest
{
    /**
     * @var \Magento\Quote\Api\CartItemRepositoryInterface
     */
    private $repository;

    /**
     * CartTest constructor.
     *
     * @param \Magento\Quote\Api\CartItemRepositoryInterface $repository
     */
    public function __construct(
        \Magento\Quote\Api\CartItemRepositoryInterface $repository
    ) {
        $this->repository = $repository;
    }

    /**
     * @param int $cartId
     *
     * @return $this
     * @throws \Magento\Framework\Exception\CouldNotSaveException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function emptyCart($cartId)
    {
        /**
         * gets all items belonging to the cart
         */
        $items = $this->repository->getList($cartId);
        foreach ($items as $item) {
            $this->repository->deleteById($cartId, $item->getItemId());
        }

        return $this;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top