hook_init() 〜 drupal_goto() を drupal8でやる方法

カテゴリ Initial コアバージョン 8.4x 関連モジュール Subscriber

modules/custom/your_module/your_module.services.yml

services:
  your_module.event_subscriber:
    class: Drupal\your_module\EventSubscriber\YourModuleSubscriber
    tags:
      - {name: event_subscriber}

modules/custom/your_module/src/EventSubscriber/Your_moduleSubscriber.php

<?php

namespace Drupal\your_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class YourModuleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    // 参考)一部の例外を除いて匿名ユーザーはloginページに飛ばす
    if (\Drupal::currentUser()->isAnonymous()) {
      if (!preg_match('!^(/user/|/sended-onetime-link-mail)!', $_SERVER['REQUEST_URI'])) {
        $path = \Drupal\Core\Url::fromUserInput('/user/login');
        $response = new RedirectResponse($path->toString());
        $response->send();
      }
    }
  }

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

}

コメント

ユーザー actbrain の写真

動的キャッシュ再生成時に来させたい場合は 優先度 > 27 にする。

    $events[KernelEvents::REQUEST][] = ['checkForRedirection', 30];

何が何でも毎回来させたい場合は 優先度 > 200 にする。

    $events[KernelEvents::REQUEST][] = ['checkForRedirection', 280];

ページ

OTHER FAQ

Drupal開発・運用の疑問/質問の答えはここに

無料ユーザー登録すると質問できます。

カテゴリ Core Ver.昇順で並び替える 関連モジュール タイトル
フォーム 7.38 Webform Webformでタクソノミーを参照したい
コンテンツの管理 7.38 Block Views node ノードページの編集タブをコンテキストメニューにしたい
フォーム 7.38 Views Views一覧の絞り込み検索フォームで複数フィールドを対象にしたい
フォーム 7.38 Webform Webformモジュールをアップデートしたら「このフィールドを入力してください」
コンテンツの作成 7.38 Webform Webformでテーブル形式にしたい
コンテンツの作成 7.38 node 代理投稿を可能にしたい
サイトの構築 7.38 deployment 冗長構成におけるアップロードおよび時間指定公開について
ユーザ 7.38 user form 新規ユーザー登録時、パスワード再設定時のパスワード入力抜けを防ぎたい
css 7.38 Webform Webfomの送信内容確認ページで表示が崩れる
コンテンツの作成 7.38 CKEditor CKEditorの「ソース」に入力したタグが消える
コンテンツの作成 7.38 node form ノード編集フォームをテーブル表示形式にしたい
サイトの環境設定 7.38 Views Bulk Operation VBO(Views Bulk Operation)で指定したアクションが表示されない
サイトの構築 7.38 Content Template ページテンプレートが反映されません。
コンテンツの作成 7.38 Views CSV出力にHTMLが入ってしまう
コンテンツの作成 7.38 CKEditor 突然GoogleMap内の経路がずれてしまった
Google 7.38 robots.txt Google Search Console Teamから「CSS および JS ファイルに Googlebot がアクセスできません」
フォーム 7.34 Webform 動的なフォーム(webform)
Messages 7.34 Disable messages 標準(コア)が表示する特定のメッセージ非表示にしたい
サイトの構築 7.34 ECK Entityの使い方について
アップデート 7.34 Core 簡単にCoreのセキュリティアップデートがしたい

ページ