1

I want to create a plugin to hook into the CouponManagement System. I hook into beforeSet and it triggers but the cart is shown as empty, This is my code:

  protected $_quote;
  private $logger;

  public function __construct(
    \Magento\Quote\Model\QuoteFactory $quoteFactory
  ){
    $this->_quote = $quoteFactory;
  }

  public function beforeSet(\Magento\Quote\Model\CouponManagement $subject, $cartId, $couponCode){
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $this->logger = $objectManager->create('\Psr\Log\LoggerInterface');
    $this->logger->debug('test before set');

    $cart = $this->_quote->create()->get($cartId);
    $this->logger->debug($cart);
  }

Can someone help me to get the actual cart?

Thank you in advance!

1 Answer 1

0

Replace

\Magento\Quote\Model\QuoteFactory $quoteFactory

with

\Magento\Quote\Api\CartRepositoryInterface $quoteRepository

and then

$cart = $this->_quote->create()->get($cartId);

change to

$cart = $this->quoteRepository->getActive($cartId);

Code Sample:

/**
 * @var \Magento\Quote\Api\CartRepositoryInterface
 */
private $quoteRepository;
private $logger;

public function __construct(
    \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
    \Psr\Log\LoggerInterface    $logger
) {

    $this->logger = $logger;
    $this->quoteRepository = $quoteRepository;
}

public function beforeSet(\Magento\Quote\Model\CouponManagement $subject, $cartId, $couponCode) {

    $this->logger->debug('test before set');

    $cart = $this->quoteRepository->getActive($cartId);
    if (!$cart->getItemsCount()) {
        //throw new \Magento\Framework\Exception\NoSuchEntityException(__('The "%1" Cart doesn\'t contain products.', $cartId));
         $this->logger->debug(__('The "%1" Cart doesn\'t contain products.', $cartId));
    }
    $this->logger->debug($cart->debug());
}
4
  • thank you for the answer. But why I only become it with $cart->debug()? $cart only gives empty response too. And how can i get the items inside?
    – vDrews
    Jun 3, 2019 at 10:56
  • have you getting the error message at Cart doesn\'t contain products at log?
    – Amit Bera
    Jun 3, 2019 at 10:58
  • use ` $this->logger->debug($cart->getId());` instread of ` $this->logger->debug($cart->debug());`
    – Amit Bera
    Jun 3, 2019 at 11:00
  • no the error message is not shown. getId() gives me the right id.
    – vDrews
    Jun 3, 2019 at 11:05

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.