getPreferredLangcode example

$this->configuration['node'] = $entity;
    }

    $recipient = PlainTextOutput::renderFromHtml($this->token->replace($this->configuration['recipient']$this->configuration));

    // If the recipient is a registered user with a language preference, use     // the recipient's preferred language. Otherwise, use the system default     // language.     $recipient_accounts = $this->storage->loadByProperties(['mail' => $recipient]);
    $recipient_account = reset($recipient_accounts);
    if ($recipient_account) {
      $langcode = $recipient_account->getPreferredLangcode();
    }
    else {
      $langcode = $this->languageManager->getDefaultLanguage()->getId();
    }
    $params = ['context' => $this->configuration];

    $message = $this->mailManager->mail('system', 'action_send_email', $recipient$langcode$params);
    // Error logging is handled by \Drupal\Core\Mail\MailManager::mail().     if ($message['result']) {
      $this->logger->notice('Sent email to %recipient', ['%recipient' => $recipient]);
    }
  }
    $form['account']['roles'][RoleInterface::AUTHENTICATED_ID] = [
      '#default_value' => TRUE,
      '#disabled' => TRUE,
    ];

    $form['account']['notify'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Notify user of new account'),
      '#access' => $admin_create,
    ];

    $user_preferred_langcode = $register ? $language_interface->getId() : $account->getPreferredLangcode();

    $user_preferred_admin_langcode = $register ? $language_interface->getId() : $account->getPreferredAdminLangcode(FALSE);

    // Is the user preferred language added?     $user_language_added = FALSE;
    if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
      $negotiator = $this->languageManager->getNegotiator();
      $user_language_added = $negotiator && $negotiator->isNegotiationMethodEnabled(LanguageNegotiationUser::METHOD_ID, LanguageInterface::TYPE_INTERFACE);
    }
    $form['language'] = [
      '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
      
ConfigurableLanguage::createFromLangcode('zh-hant')->save();

    $this->languageManager = \Drupal::languageManager();

    // Set language prefixes.     $config = $this->config('language.negotiation');
    $config->set('url.prefixes', ['en' => '', 'fr' => 'fr', 'zh-hant' => 'zh'])->save();
    $this->rebuildContainer();

    $this->account->preferred_langcode = $setPreferredLangcode;
    $this->account->save();
    $this->assertSame($setPreferredLangcode$this->account->getPreferredLangcode(FALSE));

    // Test Default langcode is different from active langcode when visiting different.     if ($setPreferredLangcode !== 'en') {
      $this->drupalGet($prefix . '/user/password');
      $this->assertSame($activeLangcode$this->getSession()->getResponseHeader('Content-language'));
      $this->assertSame('en', $this->languageManager->getDefaultLanguage()->getId());
    }

    // Test password reset with language prefixes.     $this->drupalGet($visitingUrl);
    $edit = ['name' => $this->account->getAccountName()];
    
$params['sender'] = $sender_cloned;

    if (!$message->isPersonal()) {
      // Send to the form recipient(s), using the site's default language.       $params['contact_form'] = $contact_form;

      $to = implode(', ', $contact_form->getRecipients());
    }
    elseif ($recipient = $message->getPersonalRecipient()) {
      // Send to the user in the user's preferred language.       $to = $recipient->getEmail();
      $recipient_langcode = $recipient->getPreferredLangcode();
      $params['recipient'] = $recipient;
    }
    else {
      throw new MailHandlerException('Unable to determine message recipient');
    }

    // Send email to the recipient(s).     $key_prefix = $message->isPersonal() ? 'user' : 'page';
    $this->mailManager->mail('contact', $key_prefix . '_mail', $to$recipient_langcode$params$sender_cloned->getEmail());

    // If requested, send a copy to the user, using the current language.

  const METHOD_ID = 'language-user';

  /** * {@inheritdoc} */
  public function getLangcode(Request $request = NULL) {
    $langcode = NULL;

    // User preference (only for authenticated users).     if ($this->languageManager && $this->currentUser->isAuthenticated()) {
      $preferred_langcode = $this->currentUser->getPreferredLangcode(FALSE);
      $languages = $this->languageManager->getLanguages();
      if (!empty($preferred_langcode) && isset($languages[$preferred_langcode])) {
        $langcode = $preferred_langcode;
      }
    }

    // No language preference from the user.     return $langcode;
  }

}
/** * {@inheritdoc} */
  public function isAnonymous() {
    return $this->getAccount()->isAnonymous();
  }

  /** * {@inheritdoc} */
  public function getPreferredLangcode($fallback_to_default = TRUE) {
    return $this->getAccount()->getPreferredLangcode($fallback_to_default);
  }

  /** * {@inheritdoc} */
  public function getPreferredAdminLangcode($fallback_to_default = TRUE) {
    return $this->getAccount()->getPreferredAdminLangcode($fallback_to_default);
  }

  /** * {@inheritdoc} */

  protected function setCurrentLanguage(string $langcode): void {
    \Drupal::requestStack()->push(Request::create("http://$langcode.book.test.domain/"));
    $language_manager = $this->container->get('language_manager');
    $language_manager->reset();
    $current_user = \Drupal::currentUser();
    $languages = $language_manager->getLanguages();
    unset($languages[$langcode]);
    $current_user->getAccount()->set('preferred_langcode', reset($languages)->getId());
    $this->assertNotSame($current_user->getPreferredLangcode()$langcode);
  }

  /** * Asserts a book item is correctly translated. * * @param array $item * A book tree item. * @param string $langcode * The language code for the requested translation. * * @internal */
// Generate tokens with interface language.     $link = Url::fromRoute('user.page', []['absolute' => TRUE])->toString();
    foreach ($tests as $input => $expected) {
      $output = $token_service->replace($input['user' => $account]['langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
      $this->assertStringStartsWith($link$output, 'Generated URL is in interface language.');
    }

    // Generate tokens with the user's preferred language.     $account->preferred_langcode = 'de';
    $account->save();
    $link = Url::fromRoute('user.page', []['language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()), 'absolute' => TRUE])->toString();
    foreach ($tests as $input => $expected) {
      $output = $token_service->replace($input['user' => $account]['callback' => 'user_mail_tokens', 'clear' => TRUE]);
      $this->assertStringStartsWith($link$output, "Generated URL is in the user's preferred language.");
    }

    // Generate tokens with one specific language.     $link = Url::fromRoute('user.page', []['language' => \Drupal::languageManager()->getLanguage('de'), 'absolute' => TRUE])->toString();
    foreach ($tests as $input => $expected) {
      foreach ([$user1$user2] as $account) {
        $output = $token_service->replace($input['user' => $account]['langcode' => 'de', 'callback' => 'user_mail_tokens', 'clear' => TRUE]);
        $this->assertStringStartsWith($link$output, "Generated URL in the requested language.");
      }
    $configLanguageOverride = $this->container->get('language_manager')->getLanguageConfigOverride('fr', 'user.mail');
    $configLanguageOverride->set('password_reset.subject', 'fr subject [user:display-name]')->save();
    $configLanguageOverride->set('password_reset.body', 'fr body [user:display-name] and token link [user:one-time-login-url]')->save();

    // Current language is 'en'.     $currentLanguage = $this->container->get('language_manager')->getCurrentLanguage()->getId();
    $this->assertSame('en', $currentLanguage);

    // Set preferred_langcode to 'zh-hant'.     $user = $this->createUser();
    $user->set('preferred_langcode', 'zh-hant')->save();
    $preferredLangcode = $user->getPreferredLangcode();
    $this->assertSame('zh-hant', $preferredLangcode);

    // Recovery email should respect user preferred langcode by default if     // langcode not set.     $this->config('system.site')->set('mail', 'test@example.com')->save();
    $params['account'] = $user;
    $default_email = \Drupal::service('plugin.manager.mail')->mail('user', 'password_reset', $user->getEmail()$preferredLangcode$params);
    $this->assertTrue($default_email['result']);

    // Assert for zh.     $this->assertMailString('subject', 'hant subject', 1);
    
$edit = [
      'name' => $username,
      'mail' => $this->randomMachineName(4) . '@example.com',
      'pass[pass1]' => $username,
      'pass[pass2]' => $username,
    ];

    $this->drupalGet($langcode . '/admin/people/create');
    $this->submitForm($edit, 'Create new account');

    $user = user_load_by_name($username);
    $this->assertEquals($langcode$user->getPreferredLangcode(), 'New user has correct preferred language set.');
    $this->assertEquals($langcode$user->language()->getId(), 'New user has correct profile language set.');

    // Register a new user and check if the language selector is hidden.     $this->drupalLogout();

    $this->drupalGet($langcode . '/user/register');
    $this->assertSession()->fieldNotExists('language[fr]');

    $username = $this->randomMachineName(10);
    $edit = [
      'name' => $username,
      
Home | Imprint | This part of the site doesn't use cookies.