Silverstripe Version: 4.1
Question:
I want to redirect a user to a different page but I’m not understanding how it works.
I have this requireLogin() in PageController.
public function requireLogin()
{
if ( ! $this->checkForUser())
{
# Not logged in
# Set a session message
$request = Injector::inst()->get(HTTPRequest::class);
$session = $request->getSession();
$session->set('blocked', true);
$session->set('passforward', $request->getURL());
return $this->redirect('auth/login');
}
return true;
}
I use it in another controller like this:
class AccountController extends PageController
{
private static $allowed_actions = ['settings'];
protected function init()
{
parent::init();
}
public function index(HTTPRequest $request)
{
$this->requireLogin();
$memberID = Security::getCurrentUser()->ID;
$data = [
'var' => 'things',
];
return $this->customise($data)->enderWith('Layout/Account/Index');
}
public function settings(HTTPRequest $request)
{
$this->requireLogin();
$data = [
'Title' => 'Your settings',
];
return $this->customise($data)->enderWith('Layout/Account/Settings');
}
}
When I’m logged out, going through the settings code it appears to work. I am redirected to the login page.
Going through the Index though I get an error about property of a non object where it’s trying to get the Member ID. The error is of course correct, it doesn’t exist - but why is it even trying to get there? Why didn’t it redirect before that?
If I copy that line into the settings function it makes that error too.
How do I actually redirect and stop executing code?