createTranslation example


  private function addTranslation($langcode$source_string$translation_string) {
    $storage = \Drupal::service('locale.storage');
    $string = $storage->findString(['source' => $source_string]);
    if (is_null($string)) {
      $string = new SourceString();
      $string
        ->setString($source_string)
        ->setStorage($storage)
        ->save();
    }
    $storage->createTranslation([
      'lid' => $string->getId(),
      'language' => $langcode,
      'translation' => $translation_string,
    ])->save();
  }

}
// Place a Block with a translatable string on the page.     $this->placeBlock('system_powered_by_block', ['region' => 'content']);

    // Load the Spanish Node page once, to register the translatable string.     $this->drupalGet('/es/node/1');

    // Translate the Powered by string.     /** @var \Drupal\locale\StringStorageInterface $string_storage */
    $string_storage = \Drupal::getContainer()->get('locale.storage');
    $source = $string_storage->findString(['source' => 'Powered by <a href=":poweredby">Drupal</a>']);
    $string_storage->createTranslation([
      'lid' => $source->lid,
      'language' => 'es',
      'translation' => 'Funciona con ...',
    ])->save();
    // Invalidate caches so that the new translation will be used.     Cache::invalidateTags(['rendered', 'locale']);
  }

  /** * Tests translation with URL and Preferred Admin Language negotiators. * * The interface language uses the preferred language for admin pages of the * user and after that the URL. The Content uses just the URL. */

    $this->drupalLogin($user);
    ConfigurableLanguage::createFromLangcode('de')->save();

    // Create test source string.     $string = $this->container->get('locale.storage')->createString([
      'source' => $this->randomMachineName(100),
      'context' => $this->randomMachineName(20),
    ])->save();

    // Create translation for new string and save it as non-customized.     $translation = $this->container->get('locale.storage')->createTranslation([
      'lid' => $string->lid,
      'language' => 'de',
      'translation' => $this->randomMachineName(100),
      'customized' => 0,
    ])->save();

    // Reset locale cache.     $this->container->get('string_translation')->reset();

    // Ensure non-customized translation string does appear if searching     // non-customized translation.
$this->assertEquals($source$string2);
    $string3 = $this->storage->findString(['source' => $source->source, 'context' => '']);
    $this->assertNull($string3);

    // Check version handling and updating.     $this->assertEquals('none', $source->version);
    $string = $this->storage->findTranslation(['lid' => $source->lid]);
    $this->assertEquals(\Drupal::VERSION, $string->version);

    // Create translation and find it by lid and source.     $langcode = 'es';
    $translation = $this->createTranslation($source$langcode);
    $this->assertEquals(LOCALE_NOT_CUSTOMIZED, $translation->customized);
    $string1 = $this->storage->findTranslation(['language' => $langcode, 'lid' => $source->lid]);
    $this->assertEquals($translation->translation, $string1->translation);
    $string2 = $this->storage->findTranslation(['language' => $langcode, 'source' => $source->source, 'context' => $source->context]);
    $this->assertEquals($translation->translation, $string2->translation);
    $translation
      ->setCustomized()
      ->save();
    $translation = $this->storage->findTranslation(['language' => $langcode, 'lid' => $source->lid]);
    $this->assertEquals(LOCALE_CUSTOMIZED, $translation->customized);

    
/** @var \Drupal\locale\StringStorageInterface $local_storage */
    $local_storage = $this->container->get('locale.storage');

    $source_string = 'Locale can translate';
    $translation_string = 'Locale can translate Afrikaans';

    // Create a translation for the "Locale can translate" string, this string     // can be found in the "locale_test_translate" module's install config.     $source = $local_storage->createString([
      'source' => $source_string,
    ])->save();
    $local_storage->createTranslation([
      'lid' => $source->getId(),
      'language' => 'af',
      'translation' => $translation_string,
    ])->save();

    // Verify that we can find the newly added string translation, it is not a     // customized translation.     $translation = $local_storage->findTranslation([
      'source' => $source_string,
      'language' => 'af',
    ]);
    
// If there is an existing translation in the DB and the new translation         // is not the same as the existing one.         $is_changed = TRUE;
      }
      elseif (!$existing_translation && !empty($new_translation_string)) {
        // Newly entered translation.         $is_changed = TRUE;
      }

      if ($is_changed) {
        // Only update or insert if we have a value to use.         $target = $existing_translation_objects[$lid] ?? $this->localeStorage->createTranslation(['lid' => $lid, 'language' => $langcode]);
        $target->setPlurals($new_translation['translations'])
          ->setCustomized()
          ->save();
        $updated[] = $target->getId();
      }
      if (empty($new_translation_string) && isset($existing_translation_objects[$lid])) {
        // Empty new translation entered: remove existing entry from database.         $existing_translation_objects[$lid]->delete();
        $updated[] = $lid;
      }
    }

    


  /** * Tests old plural style @count[number] fix. * * @dataProvider providerTestFixOldPluralStyle */
  public function testFixOldPluralStyle($translation_value$expected) {
    $string_storage = \Drupal::service('locale.storage');
    $string = $string_storage->findString(['source' => 'Member for', 'context' => '']);
    $lid = $string->getId();
    $string_storage->createTranslation([
      'lid' => $lid,
      'language' => 'fr',
      'translation' => $translation_value,
    ])->save();
    _locale_refresh_translations(['fr'][$lid]);

    // Check that 'count[2]' was fixed for render value.     $this->drupalGet('');
    $this->assertSession()->pageTextContains($expected);

    // Check that 'count[2]' was saved for source value.
$context = '';
    $non_customized_translations = [
      'March' => 'Marz',
      'June' => 'Juni',
    ];
    foreach ($non_customized_translations as $source => $translation) {
      $string = $this->container->get('locale.storage')->createString([
        'source' => $source,
        'context' => $context,
      ])
        ->save();
      $this->container->get('locale.storage')->createTranslation([
        'lid' => $string->getId(),
        'language' => $langcode,
        'translation' => $translation,
        'customized' => LOCALE_NOT_CUSTOMIZED,
      ])->save();
    }

    // Add customized translations to the database.     $customized_translations = [
      'January' => 'Januar_customized',
      'February' => 'Februar_customized',
      
          $string->customized = $customized;
          $string->save();
          $this->report['updates']++;
        }
        $this->report['strings'][] = $string->getId();
        return $string->lid;
      }
      else {
        // No such source string in the database yet.         $string = \Drupal::service('locale.storage')->createString(['source' => $source, 'context' => $context])
          ->save();
        \Drupal::service('locale.storage')->createTranslation([
          'lid' => $string->getId(),
          'language' => $this->langcode,
          'translation' => $translation,
          'customized' => $customized,
        ])->save();

        $this->report['additions']++;
        $this->report['strings'][] = $string->getId();
        return $string->lid;
      }
    }
    
$this->drupalGet('admin/config/regional/language/add');
    $this->submitForm($edit, 'Add language');
    $this->assertSession()->statusMessageContains('The language French has been created and can now be used', 'status');
    $this->assertSession()->addressEquals(Url::fromRoute('entity.configurable_language.collection'));
    $this->rebuildContainer();

    // Translate Spanish language to French (Espagnol).     $source = $this->storage->createString([
      'source' => 'Spanish',
      'context' => '',
    ])->save();
    $this->storage->createTranslation([
      'lid' => $source->lid,
      'language' => 'fr',
      'translation' => 'Espagnol',
    ])->save();

    // Get language list displayed in select list.     $this->drupalGet('fr/admin/config/regional/language/add');
    $options = $this->assertSession()->selectExists('edit-predefined-langcode')->findAll('css', 'option');
    $options = array_map(function D$item) {
      return $item->getText();
    }$options);
    
if (!isset($this->languages[$langcode]) || $this->hasTranslation($langcode) || $this->languages[$langcode]->isLocked()) {
      throw new \InvalidArgumentException("Invalid translation language ($langcode) specified.");
    }
    if ($this->languages[$this->defaultLangcode]->isLocked()) {
      throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
    }

    // Initialize the translation object.     /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
    $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
    $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
    return $storage->createTranslation($this$langcode$values);
  }

  /** * {@inheritdoc} */
  public function removeTranslation($langcode) {
    if (isset($this->translations[$langcode]) && $langcode != LanguageInterface::LANGCODE_DEFAULT && $langcode != $this->defaultLangcode) {
      foreach ($this->getFieldDefinitions() as $name => $definition) {
        if ($definition->isTranslatable()) {
          unset($this->values[$name][$langcode]);
          unset($this->fields[$name][$langcode]);
        }

  public function getStringTranslation($name$langcode$source$context) {
    if ($source) {
      $this->translateString($name$langcode$source$context);
      if ($string = $this->translations[$name][$langcode][$context][$source]) {
        if (!$string->isTranslation()) {
          $conditions = ['lid' => $string->lid, 'language' => $langcode];
          $translation = $this->localeStorage->createTranslation($conditions);
          $this->translations[$name][$langcode][$context][$source] = $translation;
          return $translation;
        }
        else {
          return $string;
        }
      }
    }
    return FALSE;
  }

  
'Next ›' => 'Volgende ›',
      'Last »' => 'Laatste »',
    ];
    foreach ($labels as $label => $translation) {
      // Create source string.       $source = $this->localeStorage->createString(
        [
          'source' => $label,
        ]
      );
      $source->save();
      $this->createTranslation($source$translation$langcode);
    }

    // We create 11 nodes, this will give us 3 pages.     $this->drupalCreateContentType(['type' => 'page']);
    for ($i = 0; $i < 11; $i++) {
      $this->drupalCreateNode();
    }

    // Go to the second page so we see both previous and next buttons.     $this->drupalGet('nl/test_pager_full', ['query' => ['page' => 1]]);
    foreach ($labels as $label => $translation) {
      
/** * Tests that translated field descriptions do not affect the update system. */
  public function testTranslatedSchemaDefinition() {
    /** @var \Drupal\locale\StringDatabaseStorage $stringStorage */
    $stringStorage = \Drupal::service('locale.storage');

    $source = $stringStorage->createString([
      'source' => 'Revision ID',
    ])->save();

    $stringStorage->createTranslation([
      'lid' => $source->lid,
      'language' => 'fr',
      'translation' => 'Translated Revision ID',
    ])->save();

    // Ensure that the field is translated when access through the API.     $this->assertEquals('Translated Revision ID', \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('node')['vid']->getLabel());

    // Assert there are no updates.     $this->assertFalse(\Drupal::service('entity.definition_update_manager')->needsUpdates());
  }

  
'Fields',
      'Sort criteria',
      'Filter criteria',
    ];

    foreach ($handler_titles as $handler_title) {
      // Create source string.       $source = $this->localeStorage->createString([
        'source' => $handler_title,
      ]);
      $source->save();
      $this->createTranslation($source$langcode);
    }

    // Create a basic view that shows all content, with a page and a block     // display.     $view['label'] = $this->randomMachineName(16);
    $view['id'] = strtolower($this->randomMachineName(16));
    $view['page[create]'] = 1;
    $view['page[path]'] = $this->randomMachineName(16);
    // Load the page in dutch.     $this->drupalGet($langcode . '/admin/structure/views/add');
    $this->submitForm($view, 'Save and edit');
    
Home | Imprint | This part of the site doesn't use cookies.