1

The customer has 500+ items in their cart. Items has not removed when click "Remove All" button.

The below code in resolve function is used to remove cart items

<?php
declare (strict_types = 1);

namespace Vendor\ShippingRestriction\Model\Resolver;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Query\Resolver\ArgumentsProcessorInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\QuoteGraphQl\Model\Cart\GetCartForUser;
use Magento\Quote\Api\CartItemRepositoryInterface;
use Magento\Quote\Model\MaskedQuoteIdToQuoteId;

/**
 * Class for remove items from cart
 */
class RemoveItemsFromCart implements ResolverInterface {
    /**
     * @var GetCartForUser
     */
    private $getCartForUser;

    /**
     * @var CartItemRepositoryInterface
     */
    private $cartItemRepository;

    /**
     * @var MaskedQuoteIdToQuoteId
     */
    private $maskedQuoteIdToQuoteId;

    /**
     * @var ArgumentsProcessorInterface
     */
    private $argsSelection;

    /**
     * @param GetCartForUser $getCartForUser
     * @param CartItemRepositoryInterface $cartItemRepository
     * @param MaskedQuoteIdToQuoteId $maskedQuoteIdToQuoteId
     * @param ArgumentsProcessorInterface $argsSelection
     */
    public function __construct(
        GetCartForUser $getCartForUser,
        CartItemRepositoryInterface $cartItemRepository,
        MaskedQuoteIdToQuoteId $maskedQuoteIdToQuoteId,
        ArgumentsProcessorInterface $argsSelection
    ) {
        $this->getCartForUser = $getCartForUser;
        $this->cartItemRepository = $cartItemRepository;
        $this->maskedQuoteIdToQuoteId = $maskedQuoteIdToQuoteId;
        $this->argsSelection = $argsSelection;
    }

    /**
     * Remove multiple items from cart
     */
    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) {
        $processedArgs = $this->argsSelection->process($info->fieldName, $args);
        if (empty($processedArgs['input']['cart_id'])) {
            throw new GraphQlInputException(__('Required parameter "cart_id" is missing.'));
        }
        $maskedCartId = $processedArgs['input']['cart_id'];
        try {
            $cartId = $this->maskedQuoteIdToQuoteId->execute($maskedCartId);
        } catch (NoSuchEntityException $exception) {
            throw new GraphQlNoSuchEntityException(
                __('Could not find a cart with ID "%masked_cart_id"', ['masked_cart_id' => $maskedCartId])
            );
        }
        if (empty($processedArgs['input']['cart_items']["item_id"])) {
            throw new GraphQlInputException(__('Required parameter "cart_item_id" is missing.'));
        }
        $items = $processedArgs['input']['cart_items']["item_id"];
        $storeId = (int) $context->getExtensionAttributes()->getStore()->getId();
        try {
            foreach ($items as $item){
                $this->cartItemRepository->deleteById($cartId, $item);
            }
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__('The cart doesn\'t contain the item'));
        } catch (LocalizedException $e) {
            throw new GraphQlInputException(__($e->getMessage()), $e);
        }
        $cart = $this->getCartForUser->execute($maskedCartId, $context->getUserId(), $storeId);
        return [
            'cart' => [
                'model' => $cart,
            ],
        ];
    }
}
6
  • Can you give me the file path ?
    – Himanshu
    Commented Sep 24, 2021 at 13:43
  • @Himanshu its a custom code & file
    – devhs
    Commented Sep 27, 2021 at 9:37
  • i have added full code
    – devhs
    Commented Sep 28, 2021 at 5:07
  • any thoughts on this ?
    – devhs
    Commented Sep 30, 2021 at 10:15
  • any thoughts on this ?
    – devhs
    Commented Sep 30, 2021 at 10:48

3 Answers 3

2
+50

Delete/remove the quote instead of just removing all items from cart.

    <?php
    declare (strict_types = 1);
    
    namespace Vendor\ShippingRestriction\Model\Resolver;
    
    use Magento\Framework\Exception\LocalizedException;
    use Magento\Framework\Exception\NoSuchEntityException;
    use Magento\Framework\GraphQl\Config\Element\Field;
    use Magento\Framework\GraphQl\Exception\GraphQlInputException;
    use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
    use Magento\Framework\GraphQl\Query\ResolverInterface;
    use Magento\Framework\GraphQl\Query\Resolver\ArgumentsProcessorInterface;
    use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
    use Magento\QuoteGraphQl\Model\Cart\GetCartForUser;
    use Magento\Quote\Api\CartItemRepositoryInterface;
    use Magento\Quote\Model\MaskedQuoteIdToQuoteId;
    use Magento\Quote\Api\CartRepositoryInterface;
    
    /**
     * Class for remove items from cart
     */
    class RemoveItemsFromCart implements ResolverInterface {
        /**
         * @var GetCartForUser
         */
        private $getCartForUser;
    
        /**
         * @var CartItemRepositoryInterface
         */
        private $cartItemRepository;
    
        /**
         * @var MaskedQuoteIdToQuoteId
         */
        private $maskedQuoteIdToQuoteId;
    
        /**
         * @var ArgumentsProcessorInterface
         */
        private $argsSelection;
    
        /**
         * @var CartRepositoryInterface
         */
        private $quoteRepository;
    
        /**
         * @param GetCartForUser $getCartForUser
         * @param CartItemRepositoryInterface $cartItemRepository
         * @param MaskedQuoteIdToQuoteId $maskedQuoteIdToQuoteId
         * @param ArgumentsProcessorInterface $argsSelection
         * @param CartRepositoryInterface $quoteRepository
         */
        public function __construct(
            GetCartForUser $getCartForUser,
            CartItemRepositoryInterface $cartItemRepository,
            MaskedQuoteIdToQuoteId $maskedQuoteIdToQuoteId,
            ArgumentsProcessorInterface $argsSelection,
            CartRepositoryInterface $quoteRepository
        ) {
            $this->getCartForUser = $getCartForUser;
            $this->cartItemRepository = $cartItemRepository;
            $this->maskedQuoteIdToQuoteId = $maskedQuoteIdToQuoteId;
            $this->argsSelection = $argsSelection;
            $this->quoteRepository = $quoteRepository;
        }
    
        /**
         * Remove multiple items from cart
         */
        public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) {
            $processedArgs = $this->argsSelection->process($info->fieldName, $args);
            if (empty($processedArgs['input']['cart_id'])) {
                throw new GraphQlInputException(__('Required parameter "cart_id" is missing.'));
            }
            $maskedCartId = $processedArgs['input']['cart_id'];
            try {
                $cartId = $this->maskedQuoteIdToQuoteId->execute($maskedCartId);
            } catch (NoSuchEntityException $exception) {
                throw new GraphQlNoSuchEntityException(
                    __('Could not find a cart with ID "%masked_cart_id"', ['masked_cart_id' => $maskedCartId])
                );
            }
            $storeId = (int) $context->getExtensionAttributes()->getStore()->getId();
            try {
                if($cartId){
                    $quote = $this->quoteRepository->get($cartId);
                    $quote->delete();
                }
            } catch (LocalizedException $e) {
                throw new GraphQlNoSuchEntityException(
                    __('Unable to remove item')
                );
            }
            return true;
        }
    }
0

@devhs $cartId definition is missing from your code.

Refer the below code from core:

/vendor/magento/module-quote-graph-ql/Model/Resolver/RemoveItemFromCart.php

inside resolve() method:

$cart = $this->getCartForUser->execute($maskedCartId, $context->getUserId(), $storeId);

$this->cartItemRepository->deleteById((int)$cart->getId(), $itemId);
1
  • i have added full code in question & cart is already passed.
    – devhs
    Commented Sep 28, 2021 at 5:08
0

Please try below code. This is the core function where we can use to clear the customers' cart.

protected $cart;

 
public function __construct(
    \Magento\Checkout\Model\Cart $cart
) {
    $this->cart = $cart;
}

/**
     * Empty customer's shopping cart
     *
     * @return void
     */
    protected function _emptyShoppingCart()
    {
        try {
            $this->cart->truncate()->save();
        } catch (\Magento\Framework\Exception\LocalizedException $exception) {
            $this->messageManager->addErrorMessage($exception->getMessage());
        } catch (\Exception $exception) {
            $this->messageManager->addExceptionMessage($exception, __('We can\'t update the shopping cart.'));
        }
    }
13
  • This will delete the cart as well or just the products in cart ?
    – devhs
    Commented Sep 28, 2021 at 9:55
  • It will delete quote items i.e., cart items will clear.
    – Bojjaiah
    Commented Sep 28, 2021 at 11:10
  • The cart doesn't contain the item This error i am facing, i have cross checked cart item do exist still error.
    – devhs
    Commented Sep 28, 2021 at 11:14
  • Do i need to first load the cart using the id then ->truncate()->save(); ? I am not how to use $this->cart->truncate()->save(); in the code i have added in question ?
    – devhs
    Commented Sep 28, 2021 at 11:16
  • Updated the answer. Please try now.
    – Bojjaiah
    Commented Sep 28, 2021 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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