hasTranslation example

    $this->container->get('path_alias.manager')->cacheClear();

    // Languages are cached on many levels, and we need to clear those caches.     $this->container->get('language_manager')->reset();
    $this->rebuildContainer();
    $languages = $this->container->get('language_manager')->getLanguages();

    // Ensure the node was created.     $node_storage->resetCache([$english_node->id()]);
    $english_node = $node_storage->load($english_node->id());
    $english_node_french_translation = $english_node->getTranslation('fr');
    $this->assertTrue($english_node->hasTranslation('fr'), 'Node found in database.');

    // Confirm that the alias works.     $this->drupalGet('fr' . $edit['path[0][alias]']);
    $this->assertSession()->pageTextContains($english_node_french_translation->body->value);

    // Confirm that the alias is returned for the URL. Languages are cached on     // many levels, and we need to clear those caches.     $this->container->get('language_manager')->reset();
    $languages = $this->container->get('language_manager')->getLanguages();
    $url = $english_node_french_translation->toUrl('canonical', ['language' => $languages['fr']])->toString();

    

  protected function loadRevisionTranslation(ContentEntityInterface $entity$langcode) {
    // Explicitly invalidate the cache for that node, as the call below is     // statically cached.     $this->storage->resetCache([$entity->id()]);
    $revision_id = $this->storage->getLatestTranslationAffectedRevisionId($entity->id()$langcode);
    /** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
    $revision = $revision_id ? $this->storage->loadRevision($revision_id) : NULL;
    return $revision && $revision->hasTranslation($langcode) ? $revision->getTranslation($langcode) : NULL;
  }

  /** * Returns the edit URL for the specified entity. * * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The entity being edited. * * @return \Drupal\Core\Url * The edit URL. */
  

  protected function getOriginalTranslation(ContentEntityInterface $entity, ContentEntityInterface $original) {
    // If the language of the default translation is changing, the original     // translation will be the same as the original entity, but they won't     // necessarily have the same langcode.     if ($entity->isDefaultTranslation() && $original->language()->getId() !== $entity->language()->getId()) {
      return $original;
    }
    $langcode = $entity->language()->getId();
    if ($original->hasTranslation($langcode)) {
      $original_langcode = $langcode;
    }
    else {
      $metadata = $this->contentTranslationManager->getTranslationMetadata($entity);
      $original_langcode = $metadata->getSource();
    }
    return $original->getTranslation($original_langcode);
  }

  /** * Returns the synchronized properties for every specified field. * * @param \Drupal\Core\Field\FieldDefinitionInterface[] $field_definitions * An array of field definitions. * * @return string[][] * An associative array of arrays of field property names keyed by field * name. */
        // with translations not available yet in the default revision. Thus we         // need to load the latest translation-affecting revision for each         // language to be sure we are listing all available translations.         if ($use_latest_revisions) {
          $entity = $default_revision;
          $latest_revision_id = $storage->getLatestTranslationAffectedRevisionId($entity->id()$langcode);
          if ($latest_revision_id) {
            /** @var \Drupal\Core\Entity\ContentEntityInterface $latest_revision */
            $latest_revision = $storage->loadRevision($latest_revision_id);
            // Make sure we do not list removed translations, i.e. translations             // that have been part of a default revision but no longer are.             if (!$latest_revision->wasDefaultRevision() || $default_revision->hasTranslation($langcode)) {
              $entity = $latest_revision;
            }
          }
          $translations = $entity->getTranslationLanguages();
        }

        $options = ['language' => $language];
        $add_url = $entity->toUrl('drupal:content-translation-add', $options)
          ->setRouteParameter('source', $original)
          ->setRouteParameter('target', $language->getId());
        $edit_url = $entity->toUrl('drupal:content-translation-edit', $options)
          
// On an existing entity translation, the changed timestamp will only be       // set to the request time automatically if at least one other field value       // of the entity has changed. This detection does not run on new entities       // and will be turned off if the changed timestamp is set manually before       // save, for example during migrations or by using       // \Drupal\content_translation\ContentTranslationMetadataWrapperInterface::setChangedTime().       /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
      $entity = $this->getEntity();
      /** @var \Drupal\Core\Entity\ContentEntityInterface $original */
      $original = $entity->original;
      $langcode = $entity->language()->getId();
      if (!$entity->isNew() && $original && $original->hasTranslation($langcode)) {
        $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
          $this->value = REQUEST_TIME;
        }
      }
    }
  }

}
    $executable->setExposedInput(['langcode' => '***LANGUAGE_site_default***']);
    $build = $executable->preview($display_id);
    $this->setRawContent($renderer->renderRoot($build));

    $elements = $this->cssSelect('input[type="checkbox"]');
    $this->assertCount(2, $elements, 'Both comments are visible.');
    $this->assertText($comment->label());
    $this->assertText($comment_anonymous->label());
    $executable->destroy();

    // Tests comment translation filter.     if (!$comment->hasTranslation('ur')) {
      // If we don't have the translation then create one.       $comment_translation = $comment->addTranslation('ur', ['subject' => 'ur title']);
      $comment_translation->save();
    }
    else {
      // If we have the translation then unpublish it.       $comment_translation = $comment->getTranslation('ur');
      $comment_translation->setUnpublished();
      $comment_translation->save();
    }
    if (!$comment_anonymous->hasTranslation('ur')) {
      
'langcode' => $langcode,
        'promote' => FALSE,
      ];
      $node = $this->drupalCreateNode($values);
      $this->nodes[] = $node;
    }

    // Create translations for all languages for some nodes.     for ($i = 0; $i < 2; $i++) {
      $node = $this->nodes[$i];
      foreach ($langcodes as $langcode) {
        if (!$node->hasTranslation($langcode)) {
          $title = $this->randomMachineName() . ' [' . $node->id() . ':' . $langcode . ']';
          $node->addTranslation($langcode['title' => $title, 'promote' => FALSE]);
        }
      }
      $node->save();
    }

    // Create a node with only one translation.     $node = $this->nodes[2];
    $langcode = 'en';
    $title = $this->randomMachineName() . ' [' . $node->id() . ':' . $langcode . ']';
    
return ['title' => [['value' => $this->randomMachineName()]]] + parent::getNewEntityValues($langcode);
  }

  protected function doTestBasicTranslation() {
    parent::doTestBasicTranslation();

    $storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    foreach ($this->langcodes as $langcode) {
      if ($entity->hasTranslation($langcode)) {
        $language = new Language(['id' => $langcode]);
        // Request the front page in this language and assert that the right         // translation shows up in the shortcut list with the right path.         $this->drupalGet('<front>', ['language' => $language]);
        $expected_path = \Drupal::urlGenerator()->generateFromRoute('user.page', []['language' => $language]);
        $label = $entity->getTranslation($langcode)->label();
        $this->assertSession()->elementExists('xpath', "//nav[contains(@class, 'toolbar-lining')]/ul[@class='toolbar-menu']/li/a[contains(@href, '{$expected_path}') and normalize-space(text())='{$label}']");
      }
    }
  }

  
// Normally it would make sense to load the default revision in this         // case, however that would mean simulating here the logic that we need         // to test, thus "masking" possible flaws. To avoid that, we simply         // pretend we are starting from an earlier non translated revision.         // This ensures that the we can check that the merging logic is applied         // also when adding a new translation.         $latest_affected_revision_id = 1;
      }
      $previous_revision_id = (int) $entity->getLoadedRevisionId();
      /** @var \Drupal\Core\Entity\ContentEntityInterface $latest_affected_revision */
      $latest_affected_revision = $this->storage->loadRevision($latest_affected_revision_id);
      $translation = $latest_affected_revision->hasTranslation($active_langcode) ?
        $latest_affected_revision->getTranslation($active_langcode) : $latest_affected_revision->addTranslation($active_langcode);
      $entity = $this->storage->createRevision($translation$default_revision);
      $this->assertEquals($default_revision$entity->isDefaultRevision());
      $this->assertEquals($translation->getLoadedRevisionId()$entity->getLoadedRevisionId());
      $this->assertEquals($previous_label$entity->label()$this->formatMessage('Loaded translatable field value does not match the previous one.'));
    }

    // Check that the previous untranslatable field value is loaded in the new     // revision as expected. When we are dealing with a non default translation     // the expected value is always the one stored in the default revision, as     // untranslatable fields can only be changed in the default translation or
$this->thumbnail->target_id = $this->loadThumbnail()->id();
    }
  }

  /** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    parent::postSave($storage$update);
    $is_new = !$update;
    foreach ($this->translations as $langcode => $data) {
      if ($this->hasTranslation($langcode)) {
        $translation = $this->getTranslation($langcode);
        if ($translation->bundle->entity->thumbnailDownloadsAreQueued() && $translation->shouldUpdateThumbnail($is_new)) {
          \Drupal::queue('media_entity_thumbnail')->createItem(['id' => $translation->id()]);
        }
      }
    }
  }

  /** * {@inheritdoc} */
  
    field_test_entity_info_translatable($this->entityTypeId, TRUE);
    $entity = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId)
      ->create();
    $available_langcodes = array_flip(array_keys($this->container->get('language_manager')->getLanguages()));
    $field_name = $this->fieldStorage->getName();

    // Store the field translations.     ksort($available_langcodes);
    $entity->langcode->value = key($available_langcodes);
    foreach ($available_langcodes as $langcode => $value) {
      $translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
      $translation->{$field_name}->value = $value + 1;
    }
    $entity->save();

    // Create a new revision.     $edit = [
      "{$field_name}[0][value]" => $entity->{$field_name}->value,
      'revision' => TRUE,
    ];
    $this->drupalGet($this->entityTypeId . '/manage/' . $entity->id() . '/edit');
    $this->submitForm($edit, 'Save');

    
$properties[$langcode] = [
          'name' => [0 => $this->randomMachineName()],
          'user_id' => [0 => mt_rand(128, 256)],
        ];
      }
      else {
        $properties[$langcode] = [
          'name' => [0 => $name],
          'user_id' => [0 => $uid],
        ];
      }
      $translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
      foreach ($properties[$langcode] as $field_name => $values) {
        $translation->set($field_name$values);
      }
    }
    $entity->save();

    // Check that property translation were correctly stored.     $entity = $storage->load($entity->id());
    foreach ($this->langcodes as $langcode) {
      $args = [
        '%entity_type' => $entity_type,
        
foreach ($files as $file) {
          \Drupal::service('file.usage')->add($file, 'file', $entity->getEntityTypeId()$entity->id());
        }
        return;
      }

      // Get the file IDs attached to the field before this update.       $field_name = $this->getFieldDefinition()->getName();
      $original_ids = [];
      $langcode = $this->getLangcode();
      $original = $entity->original;
      if ($original->hasTranslation($langcode)) {
        $original_items = $original->getTranslation($langcode)->{$field_name};
        foreach ($original_items as $item) {
          $original_ids[] = $item->target_id;
        }
      }

      // Decrement file usage by 1 for files that were removed from the field.       $removed_ids = array_filter(array_diff($original_ids$ids));
      $removed_files = \Drupal::entityTypeManager()->getStorage('file')->loadMultiple($removed_ids);
      foreach ($removed_files as $file) {
        \Drupal::service('file.usage')->delete($file, 'file', $entity->getEntityTypeId()$entity->id());
      }
$operations['edit'] = [
            'title' => $this->t('Edit'),
            'url' => Url::fromRoute($mapper->getBaseRouteName()$mapper->getBaseRouteParameters()['query' => ['destination' => $mapper->getOverviewPath()]]),
          ];
        }
      }
      else {
        $language_name = $language->getName();

        $operations = [];
        // If no translation exists for this language, link to add one.         if (!$mapper->hasTranslation($language)) {
          $operations['add'] = [
            'title' => $this->t('Add'),
            'url' => Url::fromRoute($mapper->getAddRouteName()$mapper->getAddRouteParameters()),
          ];
        }
        else {
          // Otherwise, link to edit the existing translation.           $operations['edit'] = [
            'title' => $this->t('Edit'),
            'url' => Url::fromRoute($mapper->getEditRouteName()$mapper->getEditRouteParameters()),
          ];

          
$node = $storage->load(1);
    $this->assertEquals('en', $node->language()->getId());
    $this->assertEquals('Cat', $node->title->value);
    $this->assertEquals('Chat', $node->getTranslation('fr')->title->value);
    $this->assertEquals('Gato', $node->getTranslation('es')->title->value);

    $node = $storage->load(2);
    $this->assertEquals('en', $node->language()->getId());
    $this->assertEquals('Dog', $node->title->value);
    $this->assertEquals('Chien', $node->getTranslation('fr')->title->value);
    $this->assertFalse($node->hasTranslation('es'), "No spanish translation for node 2");

    $node = $storage->load(3);
    $this->assertEquals('en', $node->language()->getId());
    $this->assertEquals('Monkey', $node->title->value);
    $this->assertFalse($node->hasTranslation('fr'), "No french translation for node 3");
    $this->assertFalse($node->hasTranslation('es'), "No spanish translation for node 3");

    $this->assertNull($storage->load(4), "No node 4 migrated");

    // Roll back the migrations.     foreach ($migration_ids as $migration_id) {
      
Home | Imprint | This part of the site doesn't use cookies.