Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.