Skip to main content
2 of 3
deleted 46 characters in body
May
  • 163
  • 1
  • 10

In event subscriber, how to redirect if value doesnt exist?

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 MyModuleLoad(GetResponseEvent $event) {

          $path = \Drupal::service('path.current')->getPath();

          if($path !== '/MyModulePage') {
              $event->setResponse(new RedirectResponse('/MyModulePage'));
          }
      }


  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('MyModuleLoad', 200);
    return $events;
  }
}
May
  • 163
  • 1
  • 10