1

I'm trying to send a redirect after logout, but it is not sending properly. I tried using the hook_user_logout in a module as follows:

use Drupal\Core\Routing\TrustedRedirectResponse;

function module_user_logout($account) {
  $redirect = new TrustedRedirectResponse($url);
  $redirect->send();
}

The send() call causes the page to crash with the message: "The __ page isn't working"

0

maybe because the $url is empty ?

Or maybe because you need to add return at the end of the function.

Cheers

  • If you want to ask more information about the question, you are better to leave comment under the question but not answering the question :) – Jimmy Ko Jul 21 '16 at 23:37
  • Thank you, but i didn't have enough point to comment yet. :/ – Denis Kolmerschlag Jul 22 '16 at 6:04
  • Umm... I see your pain :( – Jimmy Ko Jul 22 '16 at 7:03
0

To resolve current issue we need to create RouteSubscriber my_custom/src/EventSubscriber/MyCustomRouteSubscriber.php :

<?php

namespace Drupal\my_custom\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

    /**
     * MyCustom Route subscriber.
     */
    class MyCustomRouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = parent::getSubscribedEvents();
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -300];
        return $events;
      }

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('user.logout')) {
          $route->setDefaults([
            '_controller' => '\Drupal\my_custom\Controller\MyCustomUserLogoutController::logout',
          ]);
        }
      }

    }

Then add entry into my_custom.services.yml:

  my_custom.route_subscriber:
    class: Drupal\my_custom\EventSubscriber\MyCustomRouteSubscriber
    tags:
      - { name: event_subscriber }

Then create actual controller which will replace users module logout method. my_custom/src/Controller/MyCustomUserLogoutController.php

<?php

namespace Drupal\my_custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class MyCustomUserLogoutController.
 */
class MyCustomUserLogoutController extends ControllerBase {

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    $logout_url = 'https://google.com'
    return new TrustedRedirectResponse($logout_url);
  }

}

Hope it will save your time.

Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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