May 21, 2019 in Drupal 8, Snippets

By default you get to see a strange screen saying how long your are a member. It is good practice to auto-redirect users on login to the /admin/content page. This snippet does the trick.

use Drupal\Core\Url;
/**
 * Redirect on login.
 */
function MYMODULE_user_login($account) {
  /** @var \Drupal\user\Entity\User $account */
  /** @var \Symfony\Component\HttpFoundation\Request $request */
  if ($request = \Drupal::service('request_stack')->getCurrentRequest()) {

    if (\Drupal::service('current_route_match')->getRouteName() === 'user.reset.login') {
      return;
    }

    if ($account->hasPermission('access content overview')) {
      $request->query->set('destination', Url::fromRoute('system.admin_content', [], [
        'language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()),
      ])->toString());
    }

  }
}