How do I get the global user object in hook_preprocess_page()
?
1 Answer
<?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() Dec 1, 2015 at 8:49
-
1@KamalOberoi sure but the code is a much better example than just having those two lines IMO.– CottserDec 1, 2015 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) Apr 27, 2018 at 19:15