I have a Drupal 8 site. And I have approximately 5 pages in a site.
For example if a user hits login from the contact-us page the user should not redirect anywhere, they should stay on same page. How can I accomplish this?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI have a Drupal 8 site. And I have approximately 5 pages in a site.
For example if a user hits login from the contact-us page the user should not redirect anywhere, they should stay on same page. How can I accomplish this?
The way to solve this can be done by adding the destination
parameter to the login link.
Whenever the user is navigating a page, you update the destination based on the current page.
This can be done by implementing the hook_link_alter as the following:
/**
* Implements hook_link_alter().
*/
function custom_link_alter(&$variables) {
$routes = [
'user.login',
'user.logout',
];
/* @var Drupal\Core\Url $url */
$url = $variables['url'];
if (!$url->isExternal() && $url->isRouted() && in_array($url->getRouteName(), $routes)) {
// Get current path.
$current = \Drupal::service('path.current')->getPath();
$variables['options']['query']['destination'] = $current;
}
}
This works fine for login and also for logout links. So when user login/logout through menu link he will be redirected to the previous page.
One problem might face you with that is cache, Drupal will start caching the destination value and won't be updated when you move between pages.
You can solve this problem by implementing hook_preprocess_menu
and add destination as cache contexts.
/**
* Implements hook_preprocess_HOOK().
*/
function custom_preprocess_menu(&$variables) {
if ($variables['menu_name'] == 'account') {
$variables['#cache']['contexts'][] = 'url.query_args:destination';
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($variables, \Drupal::service('path.current')->getPath());
}
}