I want to redirect every users page to front page? like if user page url is /user/97 then it redirect to front page if user is not administrator. I want user page inaccessible to other users but only administrators.

How can I achieve this?

I tried doing like this:

<?php

namespace Drupal\myisu_ubit\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
// use Drupal\user\Entity\User;

 /**
   * Listens to the dynamic route events.
   */
 class RouteSubscriber extends RouteSubscriberBase {

 /**
  * {@inheritdoc}
  */
 protected function alterRoutes(RouteCollection $collection) {
   // Change the route associated with the user profile page (/user, /user/{uid}).
   if ($route = $collection->get('user.page')) {
      $route->setPath('/');
   } 
 }

}

module.services.yml:

services:
  user_profile.route_subscriber:
     class: Drupal\module\Routing\RouteSubscriber
     tags:
        - { name: event_subscriber }

What am I doing wrong here?

有帮助吗?

解决方案

Solved using EventSubscriber like this:

services:
  my_module.event_subscriber:
    class: Drupal\my_module\EventSubscriber\MyModuleSubscriber
    tags:
       - {name: event_subscriber}

And MyModuleSubscriber:

namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\views\Views;
use Drupal\views\ViewExecutable;
use Drupal\user\Entity\User;
use Drupal\Core\Url;

class MyModuleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public function checkForRedirection(GetResponseEvent $event) {
    $request = \Drupal::request();
    $requestUrl = $request->server->get('REQUEST_URI', NULL);
    $userID = \Drupal::currentUser()->id();
    $user = User::load($userID);
    $uid = $user->get('uid')->value;
    $roles = $user->getRoles();
    $userPage = "/user/" . $userID;
    if (
      $userID !== '1' && 
      !in_array('administrator', $roles) &&
      $requestUrl == $userPage
    ) {
        $path =  \Drupal::service('path.alias_manager')->getAliasByPath('/');
      $event->setResponse(new RedirectResponse($path, 301));
    }
  }

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

}

I don't know if it is the correct way to do this but it solves my problem.

许可以下: CC-BY-SA归因
scroll top