Created
September 29, 2016 14:03
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
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;
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);
}
This works! ⬆️
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
I couldn't get this to work, primarily because I'm working in a subdirectory. In my case,
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.