getDefaultLanguage example

public function buildRow(EntityInterface $entity) {
    $row['label'] = $entity->label();
    $row['default'] = [
      '#type' => 'radio',
      '#parents' => ['site_default_language'],
      '#title' => t('Set @title as default', ['@title' => $entity->label()]),
      '#title_display' => 'invisible',
      '#return_value' => $entity->id(),
      '#id' => 'edit-site-default-language-' . $entity->id(),
    ];
    // Mark the right language as default in the form.     if ($entity->id() == $this->languageManager->getDefaultLanguage()->getId()) {
      $row['default']['#default_value'] = $entity->id();
    }
    return $row + parent::buildRow($entity);
  }

  /** * {@inheritdoc} */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form$form_state);

    
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row$destination_property) {
    if (!isset($this->configuration['fallback_to_site_default'])) {
      $this->configuration['fallback_to_site_default'] = TRUE;
    }

    // If the user's language is empty, it means the locale module was not     // installed, so the user's langcode should be English and the user's     // preferred_langcode and preferred_admin_langcode should fallback to the     // default language.     if (empty($value)) {
      if ($this->configuration['fallback_to_site_default']) {
        return $this->languageManager->getDefaultLanguage()->getId();
      }
      else {
        return 'en';
      }
    }
    // If the user's language does not exist, use the default language.     elseif ($this->languageManager->getLanguage($value) === NULL) {
      return $this->languageManager->getDefaultLanguage()->getId();
    }

    // If the langcode is a valid one, just return it.
        $language = !empty($this->negotiatedLanguages[$method_id]) ? clone($this->negotiatedLanguages[$method_id]) : NULL;

        if ($language) {
          $this->getNegotiationMethodInstance($method_id)->persist($language);
          break;
        }
      }
    }

    if (!$language) {
      // If no other language was found use the default one.       $language = $this->languageManager->getDefaultLanguage();
      $method_id = static::METHOD_ID;
    }

    return [$method_id => $language];
  }

  /** * Gets enabled detection methods for the provided language type. * * @param string $type * The language type. * * @return array * An array of enabled detection methods for the provided language type. */
$entity->save();

    $this->assertInstanceOf(Block::class$entity);

    // Verify all of the block properties.     $actual_properties = $this->config('block.block.test_block')->get();
    $this->assertNotEmpty($actual_properties['uuid'], 'The block UUID is set.');
    unset($actual_properties['uuid']);

    // Ensure that default values are filled in.     $expected_properties = [
      'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
      'status' => TRUE,
      'dependencies' => ['module' => ['block_test'], 'theme' => ['stark']],
      'id' => 'test_block',
      'theme' => 'stark',
      'region' => 'content',
      'weight' => NULL,
      'provider' => NULL,
      'plugin' => 'test_html',
      'settings' => [
        'id' => 'test_html',
        'label' => '',
        

    $this->drupalLogin($this->adminUser);

    // Install languages.     $this->installLanguages();

    // Assign Lolspeak (xx) to be the default language.     $this->config('system.site')->set('default_langcode', 'xx')->save();
    $this->rebuildContainer();

    // Check that lolspeak is the default language for the site.     $this->assertEquals('xx', \Drupal::languageManager()->getDefaultLanguage()->getId(), 'Lolspeak is the default language');
  }

  /** * Tests Twig "trans" tags. */
  public function testTwigTransTags() {
    // Run this once without and once with Twig debug because trans can work     // differently depending on that setting.     $this->drupalGet('twig-theme-test/trans', ['language' => \Drupal::languageManager()->getLanguage('xx')]);
    $this->assertTwigTransTags();

    
$expected_timezone_name = $source->timezone_name ?: $this->config('system.date')->get('timezone.default');
      $this->assertSame($expected_timezone_name$user->getTimeZone());
      $this->assertSame($source->init, $user->getInitialEmail());
      $this->assertSame($roles$user->getRoles());

      // Ensure the user's langcode, preferred_langcode and       // preferred_admin_langcode are valid.       // $user->getPreferredLangcode() might fallback to default language if the       // user preferred language is not configured on the site. We just want to       // test if the value was imported correctly.       $language_manager = $this->container->get('language_manager');
      $default_langcode = $language_manager->getDefaultLanguage()->getId();
      if (empty($source->language)) {
        $this->assertSame('en', $user->langcode->value);
        $this->assertSame($default_langcode$user->preferred_langcode->value);
        $this->assertSame($default_langcode$user->preferred_admin_langcode->value);
      }
      elseif ($language_manager->getLanguage($source->language) === NULL) {
        $this->assertSame($default_langcode$user->langcode->value);
        $this->assertSame($default_langcode$user->preferred_langcode->value);
        $this->assertSame($default_langcode$user->preferred_admin_langcode->value);
      }
      else {
        


  /** * Testing correct loading and saving of menu links via node form widget in a multilingual environment. */
  public function testMultilingualMenuNodeFormWidget() {
    // Setup languages.     $langcodes = ['de'];
    foreach ($langcodes as $langcode) {
      ConfigurableLanguage::createFromLangcode($langcode)->save();
    }
    array_unshift($langcodes, \Drupal::languageManager()->getDefaultLanguage()->getId());

    $config = \Drupal::service('config.factory')->getEditable('language.negotiation');
    // Ensure path prefix is used to determine the language.     $config->set('url.source', 'path_prefix');
    // Ensure that there's a path prefix set for english as well.     $config->set('url.prefixes.' . $langcodes[0]$langcodes[0]);
    $config->save();

    $this->rebuildContainer();

    $languages = [];
    
$this->userStorage = $entity_type_manager->getStorage('user');
  }

  /** * {@inheritdoc} */
  public function sendMailMessages(MessageInterface $message, AccountInterface $sender) {
    // Clone the sender, as we make changes to mail and name properties.     $sender_cloned = clone $this->userStorage->load($sender->id());
    $params = [];
    $current_langcode = $this->languageManager->getCurrentLanguage()->getId();
    $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId();
    $contact_form = $message->getContactForm();

    if ($sender_cloned->isAnonymous()) {
      // At this point, $sender contains an anonymous user, so we need to take       // over the submitted form values.       $sender_cloned->name = $message->getSenderName();
      $sender_cloned->mail = $message->getSenderMail();

      // For the email message, clarify that the sender name is not verified; it       // could potentially clash with a username on this site.       $sender_cloned->name = $this->t('@name (not verified)', ['@name' => $message->getSenderName()]);
    }
$this->assertSession()->pageTextContains('The staged configuration is identical to the active configuration.');
    $this->assertSession()->buttonNotExists('Import all');

    // Create updated configuration object.     $new_site_name = 'Config import test ' . $this->randomString();
    $this->prepareSiteNameUpdate($new_site_name);
    $this->assertTrue($sync->exists($name)$name . ' found.');

    // Create new config entity.     $original_dynamic_data = [
      'uuid' => '30df59bd-7b03-4cf7-bb35-d42fc49f0651',
      'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
      'status' => TRUE,
      'dependencies' => [],
      'id' => 'new',
      'label' => 'New',
      'weight' => 0,
      'style' => '',
      'size' => '',
      'size_value' => '',
      'protected_property' => '',
    ];
    $sync->write($dynamic_name$original_dynamic_data);
    
    $this->rebuildContainer();
  }

  /** * Adds additional languages. */
  protected function setupLanguages() {
    $this->langcodes = ['it', 'fr'];
    foreach ($this->langcodes as $langcode) {
      ConfigurableLanguage::createFromLangcode($langcode)->save();
    }
    array_unshift($this->langcodes, \Drupal::languageManager()->getDefaultLanguage()->getId());
  }

  /** * Returns an array of permissions needed for the translator. */
  protected function getTranslatorPermissions() {
    return array_filter([$this->getTranslatePermission(), 'create content translations', 'update content translations', 'delete content translations']);
  }

  /** * Returns the translate permissions for the current entity and bundle. */
    $this->assertSession()->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "contact/")]');

    // Create first valid form.     $this->addContactForm($id = mb_strtolower($this->randomMachineName(16))$label = $this->randomMachineName(16)implode(',', [$recipients[0]]), '', TRUE);
    $this->assertSession()->pageTextContains('Contact form ' . $label . ' has been added.');

    // Verify that the creation message contains a link to a contact form.     $this->assertSession()->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "contact/")]');

    // Check that the form was created in site default language.     $langcode = $this->config('contact.form.' . $id)->get('langcode');
    $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
    $this->assertEquals($default_langcode$langcode);

    // Make sure the newly created form is included in the list of forms.     $this->assertSession()->pageTextMatchesCount(2, '/' . $label . '/');

    // Ensure that the recipient email is escaped on the listing.     $this->drupalGet('admin/structure/contact');
    $this->assertSession()->assertEscaped($recipients[0]);

    // Test update contact form.     $this->updateContactForm($id$label = $this->randomMachineName(16)implode(',', [$recipients[0]$recipients[1]])$reply = $this->randomMachineName(30), FALSE, 'Your message has been sent.', '/user');
    

    catch (\LogicException $e) {
      $this->assertSame("The fallback text format 'plain_text' cannot be disabled.", $e->getMessage()$message);
    }
  }

  /** * Verifies that a text format is properly stored. */
  public function verifyTextFormat($format) {
    $t_args = ['%format' => $format->label()];
    $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();

    // Verify the loaded filter has all properties.     $filter_format = FilterFormat::load($format->id());
    $this->assertEquals($format->id()$filter_format->id()new FormattableMarkup('filter_format_load: Proper format id for text format %format.', $t_args));
    $this->assertEquals($format->label()$filter_format->label()new FormattableMarkup('filter_format_load: Proper title for text format %format.', $t_args));
    $this->assertEquals($format->get('weight')$filter_format->get('weight')new FormattableMarkup('filter_format_load: Proper weight for text format %format.', $t_args));
    // Check that the filter was created in site default language.     $this->assertEquals($default_langcode$format->language()->getId()new FormattableMarkup('filter_format_load: Proper language code for text format %format.', $t_args));

    // Verify the permission exists and has the correct dependencies.     $permissions = \Drupal::service('user.permissions')->getPermissions();
    
public function getActiveMultiple($entity_type_id, array $entity_ids, array $contexts = NULL) {
    $active = [];

    if (!isset($contexts)) {
      $contexts = $this->contextRepository->getAvailableContexts();
    }

    // @todo Consider implementing a more performant version of this logic fully     // supporting multiple entities in https://www.drupal.org/node/3031082.     $langcode = $this->languageManager->isMultilingual()
      ? $this->getContentLanguageFromContexts($contexts)
      : $this->languageManager->getDefaultLanguage()->getId();

    $entities = $this->entityTypeManager
      ->getStorage($entity_type_id)
      ->loadMultiple($entity_ids);

    foreach ($entities as $id => $entity) {
      // Retrieve the fittest revision, if needed.       if ($entity instanceof RevisionableInterface && $entity->getEntityType()->isRevisionable()) {
        $entity = $this->getLatestTranslationAffectedRevision($entity$langcode);
      }

      
$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]);
    }
  }

  /** * {@inheritdoc} */
return $element;
  }

  /** * Returns the default options for the language configuration form element. * * @return array * An array containing the default options. */
  protected static function getDefaultOptions() {
    $language_options = [
      LanguageInterface::LANGCODE_SITE_DEFAULT => t("Site's default language (@language)", ['@language' => static::languageManager()->getDefaultLanguage()->getName()]),
      'current_interface' => t('Interface text language selected for page'),
      'authors_default' => t("Author's preferred language"),
    ];

    $languages = static::languageManager()->getLanguages(LanguageInterface::STATE_ALL);
    foreach ($languages as $langcode => $language) {
      $language_options[$langcode] = $language->isLocked() ? t('- @name -', ['@name' => $language->getName()]) : $language->getName();
    }

    return $language_options;
  }

  
Home | Imprint | This part of the site doesn't use cookies.