0

How to redirect if custom attribute option value != 5431 to cms page else redirect to module Controller (prescription/index).

Till now both conditions redirecting to module Controller

<?php

namespace Softadroit\Prescription\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\App\ObjectManager;
use Psr\Log\LoggerInterface;

class Orderplaceafter implements ObserverInterface
{
    protected $_responseFactory;
    protected $_url;
    protected $_order;

    public function __construct(
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Sales\Api\Data\OrderInterface $order
    ) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->_order = $order;
    }
    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {       
        $event = $observer->getEvent();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $_checkoutSession = $objectManager->create('\Magento\Checkout\Model\Session');
        $_quoteFactory = $objectManager->create('\Magento\Quote\Model\QuoteFactory');
                        
        $orderid = $observer->getEvent()->getOrderIds();
        $order = $this->_order->load($orderid);
        
        foreach($order->getItemsCollection() as $_item){        
        $product = $_item->getProductId();          
        //echo $_item->getName(); die();
        
        $is_priscription =  $_item->getProduct()->getMyCustomAttribute('prescription');         
        
        if($is_priscription != '5431'){
            $customRedirectionUrl = $this->_url->getUrl('order-success');
            return $this->_responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse();
            }
        }       
        
        $order = $_checkoutSession->getLastRealOrder();
        $quote = $_quoteFactory->create()->loadByIdWithoutStore($order->getQuoteId());
        
        if ($quote->getId()) {
            $quote->setIsActive(1)->setReservedOrderId(null)->save();
            $_checkoutSession->replaceQuote($quote);
            $url = $this->_url->getUrl('prescription/index'); //('[ModuleName]/[ModuleName]/[[Action]');
            $this->_responseFactory->create()->setRedirect($url)->sendResponse();
            die();
        }
    }
}
1
  • which observer you using ?
    – Amit Bera
    Aug 27, 2020 at 9:19

2 Answers 2

1

Redirection from observer specailly checkout_onepage_controller_success_action is not right way.

Instead of using observer, use Around Plugin on \Magento\Checkout\Controller\Onepage\Success::execute is best.

Create di.xml at app/code/VendorName/ModuleName/etc/frontend/

Add below code

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Controller\Onepage\Success">
        <plugin disabled="false" name="VendorName_ModuleName_Plugin_Frontend_Magento_Checkout_Controller_Onepage_Success" sortOrder="10" type="VendorName\ModuleName\Plugin\Frontend\Magento\Checkout\Controller\Onepage\Success"/>
    </type>
</config>

Create plugin class Success.php at app/code/VendorName/ModuleName/Plugin/Frontend/Magento/Checkout/Controller/Onepage/

<?php
namespace VendorName\ModuleName\Plugin\Frontend\Magento\Checkout\Controller\Onepage;

use Exception;
use Magento\Framework\UrlInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Sales\Api\OrderRepositoryInterface;

class Success
{
    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    private $objectManager;
    /**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    private $redirectFactory;
    /**
     * @var \Magento\Checkout\Model\Session
     */
    private $checkoutSession;
    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;
    /**
     * @var UrlInterface
     */
    private $url;
    /**
     * @var CartRepositoryInterface
     */
    private $cartRepository;
    /**
     * @var \Magento\Quote\Model\QuoteFactory
     */
    private $quoteFactory;

    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Framework\Controller\Result\RedirectFactory $redirectFactory,
        \Magento\Checkout\Model\Session $checkoutSession,
        OrderRepositoryInterface  $orderRepository,
        \Magento\Quote\Model\QuoteFactory $quoteFactory,
        UrlInterface  $url
    ) {
        $this->objectManager = $objectManager;
        $this->redirectFactory = $redirectFactory;
        $this->checkoutSession = $checkoutSession;
        $this->orderRepository = $orderRepository;
        $this->url = $url;
        $this->quoteFactory = $quoteFactory;
    }
    public function aroundExecute(
        \Magento\Checkout\Controller\Onepage\Success $subject,
        \Closure $proceed
    ) {
        $session = $this->checkoutSession;
        if (!$this->objectManager->get(\Magento\Checkout\Model\Session\SuccessValidator::class)->isValid()) {
            return $this->resultRedirectFactory->create()->setPath('checkout/cart');
        }
        $orderId = $session->getLastOrderId();
        $order  = $this->getOrder((int) $orderId);

        if (empty($orderId) ||!$order) {
            return $proceed();
        }


        $match = false;

        foreach ($order->getItemsCollection() as $_item) {
            $product = $_item->getProductId();
            $is_priscription =  $_item->getProduct()->getMyCustomAttribute('prescription');
            if ($is_priscription != '5431') {
                $match = true;
                break;
            }
        }
        if ($match) {
            /***
             * Clear Session if require
             */
            //$this->checkoutSession->clearQuote();

            $customRedirectionUrl = $this->url->getUrl('order-success');
            return $this->redirectFactory->create()->setUrl($customRedirectionUrl);
        }

        $quote = $this->getQuote((int)$order->getQuoteId());
        if ($quote && $quote->getId()) {
            /***
             * Clear Session if require
             */
            //$this->checkoutSession->clearQuote();
            $quote->setIsActive(1)->setReservedOrderId(null)->save();
            $this->checkoutSession->replaceQuote($quote);
            $url = $this->url->getUrl('prescription/index'); //('[ModuleName]/[ModuleName]/[[Action]');
            return $this->redirectFactory->create()->setUrl($url);
        }
        return $proceed();
    }
    private function getOrder($orderId)
    {
        try {
            return $this->orderRepository->get($orderId);
        } catch (Exception $exception) {
        }
        return false;
    }

    private function getQuote($quoteId)
    {
        try {
            return  $this->quoteFactory->create()->load($quoteId);
        } catch (Exception $exception) {
        }
        return false;
    }
}
11
  • it not return for both conditions can you please recheck the updated code Aug 27, 2020 at 9:17
  • Now it redirect both the to order-success Aug 31, 2020 at 6:21
  • have u checked that if ($match) { is executed?
    – Amit Bera
    Aug 31, 2020 at 6:50
  • Yes its executed but both 5431 anda !5431 redirected to success page Aug 31, 2020 at 6:52
  • okay, have u understand what is mean of if ($is_priscription != '5431') { $match = true; break; }
    – Amit Bera
    Aug 31, 2020 at 7:05
0

Here use if else condition it first match all the conditions then proceed further

<?php

namespace Softadroit\Prescription\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\App\ObjectManager;
use Psr\Log\LoggerInterface;

class Orderplaceafter implements ObserverInterface
{
    protected $_responseFactory;
    protected $_url;
    protected $_order;

    public function __construct(
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Sales\Api\Data\OrderInterface $order
    ) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->_order = $order;
    }
    
    public function execute(\Magento\Framework\Event\Observer $observer)
    {       
        $event = $observer->getEvent();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $_checkoutSession = $objectManager->create('\Magento\Checkout\Model\Session');
        $_quoteFactory = $objectManager->create('\Magento\Quote\Model\QuoteFactory');
                        
        $orderid = $observer->getEvent()->getOrderIds();
        $order = $this->_order->load($orderid);
        
        $order = $_checkoutSession->getLastRealOrder();
        $quote = $_quoteFactory->create()->loadByIdWithoutStore($order->getQuoteId());
        
        foreach($order->getItemsCollection() as $_item){        
        $product = $_item->getProductId();          
        //echo $_item->getName(); die();
        
        $is_priscription = $_item->getProduct()->getAttributeText('prescription'); 
        //echo $_item->getProduct()->getPrescription();
        //exit;
        
        if($is_priscription == '' && $is_priscription != '5431'){
             $redirectionUrl =  $this->_url->getUrl('order-success');
             $this->_responseFactory->create()->setRedirect($redirectionUrl)->sendResponse();
             return $this;
              //return;
              exit;
            }               
        
        else if($is_priscription == '' && $is_priscription != '5431' && ($quote->getId())){
            $quote->setIsActive(1)->setReservedOrderId(null)->save();
            $_checkoutSession->replaceQuote($quote);
            $url = $this->_url->getUrl('prescription/index'); //('[ModuleName]/[ModuleName]/[[Action]');
            $this->_responseFactory->create()->setRedirect($url)->sendResponse();
            die();
            
        } else if($quote->getId()) {
            $quote->setIsActive(1)->setReservedOrderId(null)->save();
            $_checkoutSession->replaceQuote($quote);
            $url = $this->_url->getUrl('prescription/index'); //('[ModuleName]/[ModuleName]/[[Action]');
            $this->_responseFactory->create()->setRedirect($url)->sendResponse();
            die();
        }
    }
}
}

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.