getLanguages example


  protected function listLanguages($flags = LanguageInterface::STATE_ALL, array $current_values = NULL) {
    $manager = \Drupal::languageManager();
    $languages = $manager->getLanguages($flags);
    $list = [];

    // The entity languages should come first, if requested.     if ($flags & PluginBase::INCLUDE_ENTITY) {
      $list['***LANGUAGE_entity_translation***'] = $this->t('Content language of view row');
      $list['***LANGUAGE_entity_default***'] = $this->t('Original language of content in view row');
    }

    // STATE_SITE_DEFAULT comes in with ID set     // to LanguageInterface::LANGCODE_SITE_DEFAULT.     // Since this is not a real language, surround it by '***LANGUAGE_...***',
return ['title' => [['value' => $this->randomMachineName()]]] + parent::getNewEntityValues($langcode);
  }

  /** * {@inheritdoc} */
  protected function doTestPublishedStatus() {
    $storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    $languages = $this->container->get('language_manager')->getLanguages();

    $statuses = [
      TRUE,
      FALSE,
    ];

    foreach ($statuses as $index => $value) {
      // (Un)publish the node translations and check that the translation       // statuses are (un)published accordingly.       foreach ($this->langcodes as $langcode) {
        $options = ['language' => $languages[$langcode]];
        
return $langcode;
  }

  /** * {@inheritdoc} */
  public function persist(LanguageInterface $language) {
    // We need to update the session parameter with the request value only if we     // have an authenticated user.     $langcode = $language->getId();
    if ($langcode && $this->languageManager) {
      $languages = $this->languageManager->getLanguages();
      if ($this->currentUser->isAuthenticated() && isset($languages[$langcode])) {
        $config = $this->config->get('language.negotiation')->get('session');
        $_SESSION[$config['parameter']] = $langcode;
      }
    }
  }

  /** * {@inheritdoc} */
  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    
'locales_location',
    ]);

    // Add new language for translation purpose.     ConfigurableLanguage::createFromLangcode('zh-hant')->save();
    ConfigurableLanguage::createFromLangcode('fr')->save();

    // Install configs.     $this->installConfig(['language', 'locale', 'user']);

    locale_system_set_config_langcodes();
    $langcodes = array_keys(\Drupal::languageManager()->getLanguages());
    $names = Locale::config()->getComponentNames();
    Locale::config()->updateConfigTranslations($names$langcodes);

    $this->config('user.settings')->set('notify.password_reset', TRUE)->save();

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

    // Reset services to apply change.     \Drupal::service('kernel')->rebuildContainer();

    

  public function updateConfigTranslations(array $names, array $langcodes = []) {
    $langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
    $count = 0;
    foreach ($names as $name) {
      $translatable = $this->getTranslatableDefaultConfig($name);
      if (empty($translatable)) {
        // If there is nothing translatable in this configuration or not         // supported, skip it.         continue;
      }

      $active_langcode = $this->getActiveConfigLangcode($name);
      $active = $this->configStorage->read($name);

      

  public function itemPage(Request $request, RouteMatchInterface $route_match$plugin_id) {
    /** @var \Drupal\config_translation\ConfigMapperInterface $mapper */
    $mapper = $this->configMapperManager->createInstance($plugin_id);
    $mapper->populateFromRouteMatch($route_match);

    $page = [];
    $page['#title'] = $this->t('Translations for %label', ['%label' => $mapper->getTitle()]);

    $languages = $this->languageManager->getLanguages();
    if (count($languages) == 1) {
      $this->messenger()->addWarning($this->t('In order to translate configuration, the website must have at least two <a href=":url">languages</a>.', [':url' => Url::fromRoute('entity.configurable_language.collection')->toString()]));
    }

    try {
      $original_langcode = $mapper->getLangcode();
      $operations_access = TRUE;
    }
    catch (ConfigMapperLanguageException $exception) {
      $items = [];
      foreach ($mapper->getConfigNames() as $config_name) {
        
return static::$filterValues = $filter_values;
  }

  /** * Lists locale translation filters that can be applied. */
  protected function translateFilters() {
    $filters = [];

    // Get all languages, except English.     $this->languageManager->reset();
    $languages = $this->languageManager->getLanguages();
    $language_options = [];
    foreach ($languages as $langcode => $language) {
      if (locale_is_translatable($langcode)) {
        $language_options[$langcode] = $language->getName();
      }
    }

    // Pick the current interface language code for the filter.     $default_langcode = $this->languageManager->getCurrentLanguage()->getId();
    if (!isset($language_options[$default_langcode])) {
      $available_langcodes = array_keys($language_options);
      
return $default;
    }

    /** * Returns the preferred language. * * @param string[] $locales An array of ordered available locales */
    public function getPreferredLanguage(array $locales = null): ?string
    {
        $preferredLanguages = $this->getLanguages();

        if (empty($locales)) {
            return $preferredLanguages[0] ?? null;
        }

        if (!$preferredLanguages) {
            return $locales[0];
        }

        $extendedPreferredLanguages = [];
        foreach ($preferredLanguages as $language) {
            
/** * Checks that workflows have the expected behaviors for the given user. * * @param \Drupal\user\UserInterface $user * The user to test the workflow behavior against. * @param array $expected_status * The an associative array with the operation name as key and the expected * status as value. */
  protected function doTestWorkflows(UserInterface $user$expected_status) {
    $default_langcode = $this->langcodes[0];
    $languages = $this->container->get('language_manager')->getLanguages();
    $options = ['language' => $languages[$default_langcode], 'absolute' => TRUE];
    $this->drupalLogin($user);

    // Check whether the user is allowed to access the entity form in edit mode.     $edit_url = $this->entity->toUrl('edit-form', $options);
    $this->drupalGet($edit_url$options);
    $this->assertSession()->statusCodeEquals($expected_status['edit']);

    // Check whether the user is allowed to access the entity delete form.     $delete_url = $this->entity->toUrl('delete-form', $options);
    $this->drupalGet($delete_url$options);
    
$criteria = new Criteria();
        $criteria->addAssociations(['language', 'languages', 'currency', 'currencies', 'domains']);
        /** @var SalesChannelCollection $salesChannels */
        $salesChannels = $this->salesChannelRepository->search($criteria, Context::createDefaultContext())->getEntities();

        $data = [];
        foreach ($salesChannels as $salesChannel) {
            /** @var LanguageEntity $language */
            $language = $salesChannel->getLanguage();
            /** @var LanguageCollection $languages */
            $languages = $salesChannel->getLanguages();
            /** @var CurrencyEntity $currency */
            $currency = $salesChannel->getCurrency();
            /** @var CurrencyCollection $currencies */
            $currencies = $salesChannel->getCurrencies();
            /** @var SalesChannelDomainCollection $domains */
            $domains = $salesChannel->getDomains();

            $data[] = [
                $salesChannel->getId(),
                $salesChannel->getName(),
                $salesChannel->getActive() ? 'active' : 'inactive',
                
$entity = $route_match->getParameter($entity_type_id);
    $account = $this->currentUser();
    $handler = $this->entityTypeManager()->getHandler($entity_type_id, 'translation');
    $manager = $this->manager;
    $entity_type = $entity->getEntityType();
    $use_latest_revisions = $entity_type->isRevisionable() && ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id$entity->bundle());

    // Start collecting the cacheability metadata, starting with the entity and     // later merge in the access result cacheability metadata.     $cacheability = CacheableMetadata::createFromObject($entity);

    $languages = $this->languageManager()->getLanguages();
    $original = $entity->getUntranslated()->language()->getId();
    $translations = $entity->getTranslationLanguages();
    $field_ui = $this->moduleHandler()->moduleExists('field_ui') && $account->hasPermission('administer ' . $entity_type_id . ' fields');

    $rows = [];
    $show_source_column = FALSE;
    /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
    $storage = $this->entityTypeManager()->getStorage($entity_type_id);
    $default_revision = $storage->load($entity->id());

    if ($this->languageManager()->isMultilingual()) {
      
    return ['name' => $this->name] + parent::getNewEntityValues($langcode);
  }

  /** * {@inheritdoc} */
  protected function doTestTranslationEdit() {
    $storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    $languages = $this->container->get('language_manager')->getLanguages();

    foreach ($this->langcodes as $langcode) {
      // We only want to test the title for non-english translations.       if ($langcode != 'en') {
        $options = ['language' => $languages[$langcode]];
        $url = $entity->toUrl('edit-form', $options);
        $this->drupalGet($url);
        $this->assertSession()->pageTextContains("{$entity->getTranslation($langcode)->label()} [{$languages[$langcode]->getName()} translation]");
      }
    }
  }

  
protected function getEditableConfigNames() {
    return ['language.mappings'];
  }

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

    // Initialize a language list to the ones available, including English.     $languages = $this->languageManager->getLanguages();

    $existing_languages = [];
    foreach ($languages as $langcode => $language) {
      $existing_languages[$langcode] = $language->getName();
    }

    // If we have no languages available, present the list of predefined languages     // only. If we do have already added languages, set up two option groups with     // the list of existing and then predefined languages.     if (empty($existing_languages)) {
      $language_options = $this->languageManager->getStandardLanguageListWithoutConfigured();
    }
public function testLanguageSorting(array $languages, ?array $expectedOrder = null): void
    {
        $request = new Request();

        foreach ($languages as &$language) {
            $language['id'] = $this->createLanguage($language['name']);
        }
        unset($language);

        $context = $this->createSalesChannelContext($this->prepareSalesChannelOverride($languages));

        $pageLanguages = $this->getPageLoader()->load($request$context)->getHeader()->getLanguages()->getElements();

        $i = 0;
        foreach ($pageLanguages as $pageLanguage) {
            static::assertSame($expectedOrder[$i]$pageLanguage->getName());
            ++$i;
        }
    }

    /** * Warning: Sorting is done after the position of the character inside the used collation. * Some characters like A and Ä share one position since Ä is being seen as A with decorations. * Adding a test case with e.g. Alang and Älang with an expected order will introduce flakynes. */
protected function createSecondStorefrontSalesChannel(): void
    {
        $salesChannelRepository = $this->getContainer()->get('sales_channel.repository');
        $criteria = (new Criteria())
            ->setIds([$this->getSalesChannelDomain()->getSalesChannelId()])
            ->addAssociation('languages');

        /** @var SalesChannelEntity $originalSalesChannel */
        $originalSalesChannel = $salesChannelRepository->search($criteria$this->context)->first();

        /** @var LanguageCollection $originalSalesChannelLanguages */
        $originalSalesChannelLanguages = $originalSalesChannel->getLanguages();
        $originalSalesChannelArray = $originalSalesChannelLanguages->jsonSerialize();
        $languages = array_map(static fn ($language) => ['id' => $language->getId()]$originalSalesChannelArray);

        $id = '000000009276457086da48d5b5628f3c';
        $data = [
            'id' => $id,
            'accessKey' => $id,
            'name' => 'A totally fake Storefront SalesChannel',
            'typeId' => Defaults::SALES_CHANNEL_TYPE_STOREFRONT,
            'customerGroupId' => TestDefaults::FALLBACK_CUSTOMER_GROUP,
            'currencyId' => Defaults::CURRENCY,
            
Home | Imprint | This part of the site doesn't use cookies.