사용자를 다른 페이지로 리디렉션하기 위해 어떤 기능 / 방법을 사용할 수 있습니까?


12

Drupal 7에서는 다음 코드를 사용합니다.

function my_goto($path) { 
  drupal_goto($path, array(), 301);
}

Drupal 8에서 어떤 코드를 사용해야합니까?


3
drupal.org/node/2023537 은 drupal_goto ()의 변경 레코드입니다. 특정 함수에 대한 대체품을 찾을 때마다 먼저 살펴보십시오.
— Berdir

답변:


24

이것은 Drupal 8에서 사용해야하는 코드입니다 . 자세한 내용은 레코드 변경을 참조하십시오 .

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_goto($path) { 
  $response = new RedirectResponse($path);
  $response->send();
  return;
}

6
추가하는 것을 잊지 마세요use Symfony\Component\HttpFoundation\RedirectResponse;
— Matt Fletcher

이것은 Symfony 애플리케이션에 적합하지 않은 저수준 HttpFoundation 코드입니다 ( symfony.com/doc/current/components/… 참조) .
— user89751

8

Anu Mathew의 응답을 바탕으로 ;

상태 코드를 추가하려면 RedirectResponse 클래스의 두 번째 매개 변수입니다.

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_goto($path) { 
  $response = new RedirectResponse($path, 302);
  $response->send();
  return;
}

1
나에게 이것은 한 번만 작동하는 것처럼 보이며 다시 작동하기를 원할 때마다 캐시를 ​​비워야합니다. 그 주위에 방법이 있습니까?
— Matt


4

drupal 8에서 아직 작업하지 않았지만 설명서에 따라 drupal_gotoDrupal 8에서 제거되었습니다.

대신에 drupal_goto다음을 작성해야합니다.

return new RedirectResponse(\Drupal::url('route.name'));

그리고 매개 변수가있는 이와 같은 것 :

return new RedirectResponse(\Drupal::url('route.name', [], ['absolute' => TRUE]));

https://www.drupal.org/node/2023537 및 클래스 RedirectResponse를 확인하십시오.


답장을 보내 주셔서 감사합니다. 그러나 현재 URL에서 경로 이름을 얻는 방법은 무엇입니까 (URL은 구성 양식을 사용하여 설정하기 때문에)
— Anu Mathew

리디렉션 경로가 동적이라는 것을 의미합니까 ???
— Sumit Madan

그렇습니다, 당신의 권리는 역동적입니다.
— Anu Mathew

Ok \Drupal::url('route.name')귀하의 URL 또는 절대 URL 로 바꾸 십시오.
— Sumit Madan

새로운 RedirectResponse ($ absolute_url); :)하지만 화면에 "redirect to example.com/absolute_url "메시지 를 보여주는
— Anu Mathew

4

내장 된 교향곡 EventDispatcher 구성 요소를 활용하여이를 수행 할 수 있습니다. 사용자 정의 모듈을 작성하기 만하면됩니다. services.yml 파일을 추가하고 적절한 서비스 구성을 제공하십시오.

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

모듈의 src 디렉토리에 eventSubscriber.php 클래스를 생성하고 여기에 메소드를 설명하십시오.

    <?php
       use Symfony\Component\HttpFoundation\RedirectResponse;

        public function checkForCustomRedirect(GetResponseEvent $event) {     
            $route_name = \Drupal::request()->attributes->get(RouteObjectInterface::ROUTE_NAME);
            if($route_name === 'module.testPage') {
              $event->setResponse(new RedirectResponse($url, $status = 302,$headers);
            }
         }

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

$ url이 정의되지 않았습니다.
— Dan Shumaker

1

나를 위해 완벽하게 작동하는 리디렉션 코드는 다음과 같습니다.

$response = new RedirectResponse($path);
return $response->send();

다른 경우에는 다음과 같은 예외 또는 오류가 발생합니다. LogicException : 컨트롤러가 응답을 반환해야합니다.

또는

https://www.drupal.org/project/drupal/issues/2852657

그것에 대한 토론이 이미 있습니다. 희망이 있습니다!


0

내부 또는 외부 리디렉션에서 작동합니다.

use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

   $url = Url::fromUri('internal:/node/27'); // choose a path
   // $url =  Url::fromUri('https://external_site.com/');
    $destination = $url->toString();
    $response = new RedirectResponse($destination, 301);
    $response->send();
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.