I implemented redirection for users when some condition become true. My code
<?php
namespace send\sms\Observer;
use Magento\Framework\Registry;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\ManagerInterface;
class check implements ObserverInterface
{
protected $redirect;
protected $_customerSession;
protected $_objectManager;
protected $_urlInterface;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\App\Response\RedirectInterface $redirect,
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\UrlInterface $urlInterface
) {
$this->_customerSession = $customerSession;
$this->redirect = $redirect;
$this->_objectManager = $objectManager;
$this->_urlInterface = $urlInterface;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$actionName = $observer->getEvent()->getRequest()->getFullActionName();
$controller = $observer->getControllerAction();
$obm = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\Http\Context $context */
$context = $obm->get('Magento\Framework\App\Http\Context');
/** @var bool $isLoggedIn */
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if($isLoggedIn){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $om->create('Magento\Customer\Model\Session');
$suser_id = $customerSession->getCustomer()->getId();
$this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection');
$connection= $this->_resources->getConnection();
$tableName = $this->_resources->getTableName('otpp');
$sql = "SELECT verified FROM otpp WHERE `entity_id`='$suser_id'";
$result = $connection->fetchall($sql);
@$otparray = $result['0'];
$verified = $otparray['verified'];
if($verified == 0) {
$url = $this->_urlInterface->getUrl('otp/index/index'); // give here your controller/action
// below code redirects to cart controller
$observer->getControllerAction()
->getResponse()
->setRedirect($url);
}
}
}
}