0

I have create a EventSubscriber like this:

<?php

namespace Drupal\custom_session\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class SessionInitial.
 */
class SessionInitial implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['setSession'];

    return $events;
  }

  /**
   * This method is called whenever the kernel.request event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function setSession(Event $event) {
    // Start request.
    kint($_SESSION['page']);
    $route_name = \Drupal::routeMatch()->getRouteName();
    if ($route_name == 'view.frontpage.page_1') {
      $_SESSION['page'] = 'Home page';
    }
    else {
      $_SESSION['page'] = 'Other page';
    }
    // End logic.
    kint($_SESSION['page']);
  }

}

Every request I'll check prev $_SESSION['page'] and process logic.

But each request $_SESSION['page'] all has same value Other page.

Test step by step:

1, Go to home page (router name is **view.frontpage.page_1)**

enter image description here

2. Refesh browser with url home page but debug result is the same:

enter image description here

Also last request was set $_SESSION['page'] to Home Page. I don't know why. Someone can help me. Thanks!

2
  • 1
    Probably "Other page" is from a subrequest, but this is hard to tell without xdebug, also because you have more kint messages than the code can produce. If you use kint, why not output more data, like the route name and if it is the master request $event->isMasterRequest?
    – 4uk4
    May 18, 2018 at 13:29
  • @4k4 thank you for support! With your suggestion I using Drupal log to log router name when has request. Can't using die() or kint() because it is sub request. I and found the problem that after home page request has a sub request is quickedit.attachments.
    – Jonh
    May 18, 2018 at 14:06

1 Answer 1

1

With @4k4's suggestion, I found the problem. After each request has a ajax request. The request has route name is quickedit.attachments and method post. So I edited code like that:

public function setSession(Event $event) {
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (!$event->getRequest()->isXmlHttpRequest()) {
      if ($route_name == 'view.frontpage.page_1') {
        $_SESSION['page'] = 'Home page';
      }
      else {
        $_SESSION['page'] = 'Other page';
      }
    }
  }

Now it's working good. Thanks!

Not the answer you're looking for? Browse other questions tagged or ask your own question.