3

I'm using Magento 2.1.3

I have an observer 'sales_order_place_before', I want to validate some information before the payment is made and if validation is false, I want to redirect the page to 'checkout/cart' with error message.

Please see the below code , my page is response is being rendered but not redirected. Thanks!

Observer file

Vendor/Module/Observer/ValidateUserDetails.php

<?php

namespace Smartshore\Incase\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\ManagerInterface;

class ValidateUserDetails implements ObserverInterface
{ 

    protected $messageManager;
    protected $_responseFactory;
    protected $_url;

    public function __construct(\Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url
    ) {
        $this->messageManager = $messageManager;
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }



    /**
    * @param EventObserver $observer
    * @return $this
    * @SuppressWarnings(PHPMD.CyclomaticComplexity)
    */
    public function execute(EventObserver $observer)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $helperFactory = $objectManager->create('Smartshore\Incase\Helper\Data');

        $order = $observer->getOrder(); 
        $orderData = $order->getData();

        $urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
        $url = $urlInterface->getUrl('/');

        $customerId = $orderData['customer_id']; 
        $customerEmail = $orderData['customer_email']; 
        $customerFirstname  = $orderData['customer_firstname']; 
        $customerMiddlename = $orderData['customer_middlename']; 
        $customerLastname = $orderData['customer_lastname']; 

        $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 
        $items = $cart->getItems();

        $infoArr = array();

        if (!empty($items)) {

            foreach ($items as $key => $item) {

                $options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
                $customOptions = $options['options'];

                if (!empty($customOptions)) {

                    $infoArr[$customerEmail][] = array(

                        'userData' => array(
                            'email' => $customOptions[0]['value'],
                            'dob' => $customOptions[1]['value'],
                            'firstName' => $customOptions[2]['value'],
                            'lastName' => $customOptions[3]['value']
                        ),

                        'trainingId' => $customOptions[4]['value']
                    );
                }
            }
        }

        if (!empty($infoArr)) {

            //runCurl and get response

            $response = array('status' => 'error');

            if (isset($response['status']) && $response['status'] == 'error') {

                $this->messageManager->addError(__('We can\'t void the payment right now.'));

                $cartUrl = $this->_url->getUrl('/');
                $this->_responseFactory->create()->setRedirect($cartUrl);
            }
        }
    }
}

events.xml file

Vendor/Module/etc/webapi_rest/events.xml

<?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="sales_order_place_before">
       <observer name="order_place_before" instance="Smartshore\Incase\Observer\ValidateUserDetails" shared="false" />
    </event>  
</config>

2 Answers 2

1

I think you've done most things right but you missed to add correct parameter in getUrl() fuction . It should be :

$cartUrl = $this->_url->getUrl('checkout/cart/index');
8
  • it still redirects to success page
    – anujeet
    Mar 20, 2017 at 13:14
  • I think you have to exit; after $this->_responseFactory->create()->setRedirect($cartUrl); Mar 20, 2017 at 13:15
  • it redirects to cart page, because of exit, suppose I want to redirect to 'contact/index/index'. if I use exit , then it wlll redirect to cart page irresepective of the url I have given. This is the main problem I'm facing
    – anujeet
    Mar 20, 2017 at 13:18
  • try $this->_responseFactory->create()->setRedirect($cartUrl)->sendResponse(); Mar 20, 2017 at 13:21
  • this is also not working, because the redirect is not working from here. with the exit expression redirect works from magento default function. I don't know from where
    – anujeet
    Mar 20, 2017 at 13:30
1

Updated solution:

 if(Your_condition)
 {
 }
 else
 {
    $customerBeforeAuthUrl = $this->_url->getUrl('checkout/cart/index');
          $this->_responseFactory->create()->setRedirect($customerBeforeAuthUrl)->sendResponse();
      exit;
 }

NOTE: CODE TESTED

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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