Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Get the current user in drupal 8

By editor , 2 December, 2015
Question
  • How to get the current user, user ID, user data on drupal 8 ?
  • How To check if the current page is the homepage of Drupal 8 ?

Example:

    //use Drupal\user\Entity\User;
    $userCurrent = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($userCurrent->id());
    $name = $user->getUsername();

 

How To check if the current page is the homepage in Drupal 8

As drupal_is_front_page() on drupal 7, you can use path.matcher service of drupal 8.
Example:
$is_front_page = \Drupal::service('path.matcher')->isFrontPage();

Tags

  • Drupal 8
  • User
  • Code
  • Add new comment

Comments3

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Rendhon (not verified)

10 years 2 months ago

Display this in a twig template

How can i able to add this in my twig template file.??

  • Reply

editor

10 years 2 months ago

Use custom module to show variable or alter your template

For that, use a custom module like here
Example : (Custom page)

return array(
      '#theme' => 'tour_custon_theme',
      '#user' => $user,
    );

//OR with inline template
return array(
      '#type' => 'inline_template',
      '#template' => '{{ user }}',
      '#context' => array(
        'user' => $user,
      ),
    );

If you can't do this, try to use the hook template_preprocess like:

function template_preprocess_YOURTEMPLATE(&$variables) {
}

  • Reply

Anonymous (not verified)

8 years 9 months ago

$userCurrent = \Drupal:…

$userCurrent = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($userCurrent->id());
    $name = $user->getUsername();

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer