You are here

public function User::getPreferredLangcode in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/user/src/Entity/User.php \Drupal\user\Entity\User::getPreferredLangcode()

Returns the preferred language code of the account.

Parameters

bool $fallback_to_default: (optional) Whether the return value will fall back to the site default language if the user has no language preference.

Return value

string Returned language code depends upon following:

  • The user preferred language code is returned if set in the account.
  • If the user has no preferred language and $fallback_to_default is TRUE then the site default language code is returned.
  • If the user has no preferred language and $fallback_to_default is FALSE then empty string is returned.

Overrides AccountInterface::getPreferredLangcode

File

core/modules/user/src/Entity/User.php, line 326

Class

User
Defines the user entity class.

Namespace

Drupal\user\Entity

Code

public function getPreferredLangcode($fallback_to_default = TRUE) {
  $language_list = $this
    ->languageManager()
    ->getLanguages();
  $preferred_langcode = $this
    ->get('preferred_langcode')->value;
  if (!empty($preferred_langcode) && isset($language_list[$preferred_langcode])) {
    return $language_list[$preferred_langcode]
      ->getId();
  }
  else {
    return $fallback_to_default ? $this
      ->languageManager()
      ->getDefaultLanguage()
      ->getId() : '';
  }
}