Skip to content

Instantly share code, notes, and snippets.

@annikaC
Created September 29, 2016 14:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save annikaC/722f0a38e734c087d6f0779a1aef6f3b to your computer and use it in GitHub Desktop.
Save annikaC/722f0a38e734c087d6f0779a1aef6f3b to your computer and use it in GitHub Desktop.
Drupal 8 redirect user to own user edit page (for use in menu links)
<?php
namespace Drupal\yourmodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* A controller that redirects to the current user's edit account page.
*/
class AccountEditRedirectController extends ControllerBase {
/**
* Redirect to
*/
public function redirect_to_account_edit() {
global $base_url;
$path = \Drupal\Core\Url::fromRoute('entity.user.edit_form', ['user' => \Drupal::currentUser()->id()])->toString();
$response = new RedirectResponse($base_url . $path);
$response->send();
}
}
yourmodule.account_edit_redirect:
path: '/user/me/edit'
defaults:
_controller: '\Drupal\yourmodule\Controller\AccountEditRedirectController::redirect_to_account_edit'
requirements:
_role: 'authenticated'
@NikLP
Copy link

NikLP commented Mar 22, 2017

I couldn't get this to work, primarily because I'm working in a subdirectory. In my case,

$path = /test/web/user/1/edit and 
global $base_url = http://dev.kinetasystems.com/test/web

but global $base_root = http://dev.kinetasystems.com so I suspect the correct approach is $response = new RedirectResponse($base_root . $path);, having declared the appropriate global @annikaC?

Also while I'm looking throught this stuff, I think it would be better to validate the route using _user_is_logged_in: 'TRUE' rather than just the role, which could be confused.

@NikLP
Copy link

NikLP commented Sep 6, 2017

Also as per https://drupal.stackexchange.com/questions/146185/how-to-create-a-redirection-in-drupal-8 - you need to return the response object not whatever that is. Otherwise you get

LogicException: The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?

    // $response->send();
    // return;
    return $response;

@szeidler
Copy link

szeidler commented May 7, 2018

If you're redirecting to routes, you can utilize the $this->redirect() method. Then you don't work with URLs and don't need to trreat the base_url.

public function redirect_to_account_edit() {
    $route_name = 'entity.user.edit_form';
    $route_parameters = [
      'user' => \Drupal::currentUser()->id(),
    ];

    return $this->redirect($route_name, $route_parameters);
}

@heitoralthmann
Copy link

This works! ⬆️

@annikaC
Copy link
Author

annikaC commented Oct 16, 2019

I had totally forgotten about this gist! Thanks for commenting with your updates :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment