1

I want to prevent order on checkout page. With the use of particular condition i need stop placing order.

When i click on place order button , my order should not be place and should redirect to cart page with error message.

Do anyone have idea on this?

Thanks!

2
  • Try to use this event: sales_order_place_before Commented Apr 23, 2021 at 5:12
  • Not working as per my requirement
    – ZealousWeb
    Commented Apr 23, 2021 at 5:20

1 Answer 1

-1

Observer on event sales_order_place_before can prevent the order being placed. Example, if the order is below $100, order won't be placed, and the message will appear in checkout page. getData('order') returns Magento/Sales/Model/Order object. If you need to check the order items, you can use $order->getAllItems()

namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Message\ManagerInterface as MessageManagerInterface;

class PreventOrder implements ObserverInterface
{

public function __construct(
   MessageManagerInterface $messageManager
) {
   $this->messageManager = $messageManager;
}

/**
 * @param Observer $observer
 * @return $this
 */
public function execute(Observer $observer)
 {
   $order = $observer->getEvent()->getData('order');
   $orderTotal = $order->getTotalDue();
   $threshold = 100;

   try {
     if ($orderTotal < $threshold) {
       $message = "Order is below the $100 minimum required!";
       $this->messageManager->addError(__($message));
       $this->_redirect('checkout/cart');
       return;
     }
   } catch (\Magento\Framework\Exception\Exception $e) {
     throw new \Magento\Framework\Exception\LocalizedException(
       __($e->getMessage())
     );
   }
 }

}

etc/events.xml file

  <event name="sales_order_place_before">
      <observer name="vendor_module_preventOrder" 
                instance="Vendor\Module\Observer\PreventOrder"/>
  </event>

enter image description here

7
  • I need to redirect to cart page with error message and don't want to throw exception. I can easily redirect to cart page but error message was not showing. You can try practically for it
    – ZealousWeb
    Commented Apr 23, 2021 at 5:38
  • I updated the code to add error message and redirect.
    – bernieu2
    Commented Apr 23, 2021 at 5:56
  • Hey bro, i know the code. I am saying this you can check by practically. You will not see error message after redirect.
    – ZealousWeb
    Commented Apr 23, 2021 at 5:57
  • I am seeing error message in my installation?
    – bernieu2
    Commented Apr 23, 2021 at 5:59
  • In which version you are working?
    – ZealousWeb
    Commented Apr 23, 2021 at 6:04

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.