2

I am attempting to add some code to a hook_entity_view_alter() function to redirect the user to the homepage under a rare condition with RedirectResponse.

I understand the method to accomplish this is along these lines (taken from here):

$response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
$response->send(); // don't send the response yourself inside controller and form.
return;

My issue is that I am not sure how to format $url. Most articles on the topic, such as this one, suggest using \Drupal::url(), but this is deprecated in favour of Drupal\Core\Url. I would like to avoid using deprecated methods as much as possible, but am stuck at trying to figure out what the Drupal\Core\Url equivalent is to \Drupal::url('<front>'). I am not sure which methods to be using, and nothing I've tried with Url::fromUri() has worked.

2

Try using Url::fromInternalUri then instead of fromUri():

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Url.php/function/Url%3A%3AfromInternalUri/8.2.x

It specifically notes the use of front and none. But you can't pass the URL object or path tokens to RedirectResponse, as this is a Drupal construct. That class expects the following arguments:

http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/RedirectResponse.html

string  $url        The URL to redirect to
integer $status     The response status code
array   $headers    An array of response headers

$url needs to be a string, so on your URL object, call ->toString() to get the URL.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AtoString/8.2.x

  • I've tried Url::fromInternalUri(), but it's protected and can't be called from my function. I have also tried Url::fromUri('internal:/', array('absolute' => true))->toString() but this causes a browser crash from too many redirects. Url::fromUri('<front>')->toString() also does not work: "InvalidArgumentException: The URI '<front>' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 280 of core\lib\Drupal\Core\Url.php)." – saramm1 Sep 6 '16 at 14:55
  • Oh, wait a sec, the test function I was using had something strange going on in it. $response = new Symfony\Component\HttpFoundation\RedirectResponse(Url::fromUri('internal:/', array('absolute' => true))->toString()); works. – saramm1 Sep 6 '16 at 15:04
  • @saramm1 $response = new Symfony\Component\HttpFoundation\RedirectResponse(Url::fromU‌​ri('internal:/', array('absolute' => true))->toString()); this has got some mistakes in it, can you please check and write the correct one? – Gaurav Rajdeo Sep 30 '17 at 12:07

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.