0

How do I get the global user object in hook_preprocess_page()?

7
<?php
public function behave() {
  $account = \Drupal::currentUser();
  if ($account->id() == 1) {
    return "Hi, boss!";
  }
  else {
    return "You are not the site administrator.";
  }
}
?>

Note that in neither case is the value an actual User object. Rather, as of Drupal 8 it is a UserSession object, which duplicates some, but not all, of the information of a user. It may also represent the Anonymous User rather than a saved User entity. See link for more information.

  • only two lines are sufficient $account = \Drupal::currentUser(); $account->id() – Kamal Oberoi Dec 1 '15 at 8:49
  • 1
    @KamalOberoi sure but the code is a much better example than just having those two lines IMO. – Cottser Dec 1 '15 at 20:47
  • $account->id() is returning string not integer so if you want to compare with an integer value you should us if ((int) $account->id() == 1) – Yogesh Kushwaha Apr 27 '18 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.