Skip to content

Instantly share code, notes, and snippets.

@magevision
Created October 1, 2018 08:46
Show Gist options
  • Save magevision/a9739b8feaadd30b8a7aac4a59f98a3d to your computer and use it in GitHub Desktop.
Save magevision/a9739b8feaadd30b8a7aac4a59f98a3d to your computer and use it in GitHub Desktop.
ValidateCartBeforeCheckout
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_index_index">
<observer name="validate_cart" instance="MageVision\Blog32\Observer\ValidateCartObserver" />
</event>
</config>
<?php
namespace MageVision\Blog32\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Checkout\Model\Cart as CustomerCart;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\App\Response\RedirectInterface;
use Magento\Framework\Event\Observer;
class ValidateCartObserver implements ObserverInterface
{
/**
* @var ManagerInterface
*/
protected $messageManager;
/**
* @var RedirectInterface
*/
protected $redirect;
/**
* @var Cart
*/
protected $cart;
/**
* @param ManagerInterface $messageManager
* @param RedirectInterface $redirect
* @param CustomerCart $cart
*/
public function __construct(
ManagerInterface $messageManager,
RedirectInterface $redirect,
CustomerCart $cart
) {
$this->messageManager = $messageManager;
$this->redirect = $redirect;
$this->cart = $cart;
}
/**
* Validate Cart Before going to checkout
* - event: controller_action_predispatch_checkout_index_index
*
* @param Observer $observer
* @return void
*/
public function execute(Observer $observer)
{
$quote = $this->cart->getQuote();
$controller = $observer->getControllerAction();
$cartItemsQty = $quote->getItemsQty();
//If cart item qty is lower than 4 then redirect to the cart with a message
if ($cartItemsQty < 4) {
$this->messageManager->addNoticeMessage(
__('Please review your cart!')
);
$this->redirect->redirect($controller->getResponse(), 'checkout/cart');
}
}
}
@myselfhimself
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment