I am trying to check a condition before page load, if value exists to load page if not to redirect.
I am following this page
I have created a /mymodule/mymodule.services.yml file and a /mymodule/src/MyModuleSubscriber.php file.
In MyModuleSubscriber.php I would like to check if a value exists, if it does to load site as normal, if the value doesn't exist to perform redirect.
This is the code, but not sure how to write it correctly. Do I need to put an else statement or just leave blank?
Is this correct way to check a value exists on every page load?
class MyModuleSubscriber implements EventSubscriberInterface {
public function checkForRedirect(GetResponseEvent $event) {
$baseUrl = $event->getRequest()->getBaseUrl();
if($value == null &&
$baseURL !== '/MyModulePage') {
$event->setResponse(new RedirectResponse($baseUrl.'/MyModulePage'));
}
}
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('MyModuleLoad', 200);
return $events;
}
}
Edit:
$path = \Drupal::service('path.current')->getPath();
if($path !== '/MyModulePage') {
$event->setResponse(new RedirectResponse('/MyModulePage'));
}
path.current
is updated during routing, this early you have to get the path from$event->getRequest()->getPathInfo()
.