I know this question has been asked before a couple of times here:
Magento 2 : Redirect From Homepage to Login if not Logged
Magento 2 - Redirect user to a specific page if not logged in
However i cant seem to get it to work and am a bit confused about how this works with my specific controller. So far I have created an event.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="controller_action_predispatch">
<observer name="check_login_persistent" instance="Vendor\Module\Observer\CheckLoginPersistentObserver" />
</event>
</config>
This then references the observer:
<?php
namespace Vendor\Module\Observer;
class CheckLoginPersistentObserver implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Magento\Framework\App\Response\RedirectInterface
*/
protected $redirect;
/**
* Customer session
*
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;
public function __construct(
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\App\Response\RedirectInterface $redirect
) {
$this->_customerSession = $customerSession;
$this->redirect = $redirect;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
echo "This is an event";
$actionName = $observer->getEvent()->getRequest()->getFullActionName();
$controller = $observer->getControllerAction();
$openActions = array(
'create',
'createpost',
'login',
'loginpost',
'logoutsuccess',
'forgotpassword',
'forgotpasswordpost',
'resetpassword',
'resetpasswordpost',
'confirm',
'confirmation'
);
if ($controller == 'account' && in_array($actionName, $openActions)) {
return $this; //if in allowed actions do nothing.
}
if(!$this->_customerSession->isLoggedIn()) {
$this->redirect->redirect($controller->getResponse(), 'customer/account/login');
}
}
}
Then im not sure how to make this work in my specific case for my controller. I have looked a bit at events and added the below code to my controller so the event is fired:
$this->_eventManager->dispatch('controller_action_predispatch');
However this has ended up showing an error:
PHP Fatal error: Uncaught Error: Call to a member function getRequest() on null in /var/www/magento2/public_html/vendor/magento/module-customer/Model/Visitor.php