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'
@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