0

I have created an observer event in custom extension. I want to check something before order will be created. When condition not true then checkout process schould be break and go back to cart. Here is my code

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_before">
       <observer name="company_module_observer_check" instance="Company\Module\Observer\Check" />
   </event> 
</config>

and

class Check implements \Magento\Framework\Event\ObserverInterface
{

    /** @var  LoggerInterface */
    protected $logger;
    /**
     *
     * @param LoggerInterface $logger
     * @param array $data
     */
    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {

       //TOTO i want do things like below
        $condition // condition will be got from an API service 
        if($condition){
             return $this;
        }else{
            return // Go back to cart
        }
    }
}

Can somebody help me?

1
  • 1
    try to throw a exception?
    – Anton S
    Feb 24, 2017 at 17:11

1 Answer 1

0

You can used code like this :

class Check implements \Magento\Framework\Event\ObserverInterface
{

    protected $_responseFactory;
    protected $_url;
    protected $logger;

    public function __construct(\Magento\Framework\App\ResponseFactory $responseFactory, \Magento\Framework\UrlInterface $url,LoggerInterface $logger) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url; 
        $this->logger = $logger;
    }
    enter code here
    public function execute(\Magento\Framework\Event\Observer $observer)
    {

       //TOTO i want do things like below
        $condition // condition will be got from an API service 
        if($condition){
             return $this;
        }else{
            // Go back to cart
            $cartUrl = $this->_url->getUrl('checkout/cart/index');
            $this->_responseFactory->create()->setRedirect($cartUrl)->sendResponse();            
            exit;
        }
    }
}

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.