getUntranslated example


function hook_entity_translation_insert(\Drupal\Core\Entity\EntityInterface $translation) {
  $variables = [
    '@language' => $translation->language()->getName(),
    '@label' => $translation->getUntranslated()->label(),
  ];
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
}

/** * Respond to creation of a new entity translation of a particular type. * * This hook runs once the entity translation has been stored. Note that hook * implementations may not alter the stored entity translation data. * * @param \Drupal\Core\Entity\EntityInterface $translation * The entity object of the translation just stored. * * @ingroup entity_crud * @see hook_entity_translation_insert() */
    // original object behave independently.     $name = $default_langcode . '_' . $this->randomMachineName();
    $entity->name->value = $name;
    $name_translated = $langcode . '_' . $this->randomMachineName();
    $translation = $entity->addTranslation($langcode);
    $this->assertTrue($translation->isNewTranslation(), 'Newly added translations are marked as new.');
    $this->assertNotSame($entity$translation, 'The entity and the translation object differ from one another.');
    $this->assertTrue($entity->hasTranslation($langcode), 'The new translation exists.');
    $this->assertEquals($langcode$translation->language()->getId(), 'The translation language matches the specified one.');
    $this->assertEquals($langcode$translation->{$langcode_key}->value, 'The translation field language value matches the specified one.');
    $this->assertFalse($translation->{$default_langcode_key}->value, 'The translation object is not the default one.');
    $this->assertEquals($default_langcode$translation->getUntranslated()->language()->getId(), 'The original language can still be retrieved.');
    $translation->name->value = $name_translated;
    $this->assertEquals($name$entity->name->value, 'The original name is retained after setting a translated value.');
    $entity->name->value = $name;
    $this->assertEquals($name_translated$translation->name->value, 'The translated name is retained after setting the original value.');

    // Save the translation and check that the expected hooks are fired.     $translation->save();
    $hooks = $this->getHooksInfo();

    $this->assertEquals($langcode$hooks['entity_translation_create'], 'The generic entity translation creation hook has fired.');
    $this->assertEquals($langcode$hooks[$entity_type . '_translation_create'], 'The entity-type-specific entity translation creation hook has fired.');

    
$active = $this->entityRepository->getActive($entity_type_id$entity->id()$it_contexts);
    $this->assertSame($it_revision->getLoadedRevisionId()$active->getLoadedRevisionId());
    $this->assertSame($it_revision->language()->getId()$active->language()->getId());

    /** @var \Drupal\Core\Entity\ContentEntityInterface $it_revision2 */
    $it_revision2 = $storage->createRevision($it_revision);
    $storage->save($it_revision2);

    $active = $this->entityRepository->getActive($entity_type_id$entity->id()$en_contexts);
    $this->assertSame($it_revision2->getLoadedRevisionId()$active->getLoadedRevisionId());
    $this->assertSame($it_revision2->getUntranslated()->language()->getId()$active->language()->getId());

    $active = $this->entityRepository->getActive($entity_type_id$entity->id()$it_contexts);
    $this->assertSame($it_revision2->getLoadedRevisionId()$active->getLoadedRevisionId());
    $this->assertSame($it_revision2->language()->getId()$active->language()->getId());

    /** @var \Drupal\entity_test\Entity\EntityTestMulRev $entity2 */
    $entity2 = $storage->create($values);
    $storage->save($entity2);
    /** @var \Drupal\Core\Entity\ContentEntityInterface[] $active */
    $active = $this->entityRepository->getActiveMultiple($entity_type_id[$entity->id()$entity2->id()]$it_contexts);
    $this->assertSame($it_revision2->getLoadedRevisionId()$active[$entity->id()]->getLoadedRevisionId());
    
->getStorage($entity->getEntityTypeId())
        ->loadRevision($entity->getLoadedRevisionId());
    }

    foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
      if (in_array($field_name$skip_fields, TRUE) || $definition->isTranslatable() || $definition->isComputed()) {
        continue;
      }

      $items = $entity->get($field_name)->filterEmptyItems();
      $original_items = $original->get($field_name)->filterEmptyItems();
      if ($items->hasAffectingChanges($original_items$entity->getUntranslated()->language()->getId())) {
        return TRUE;
      }
    }

    return FALSE;
  }

}
/** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $this->getEntity();
    $message = $this->getDeletionMessage();

    // Make sure that deleting a translation does not delete the whole entity.     if (!$entity->isDefaultTranslation()) {
      $untranslated_entity = $entity->getUntranslated();
      $untranslated_entity->removeTranslation($entity->language()->getId());
      $untranslated_entity->save();
      $form_state->setRedirectUrl($untranslated_entity->toUrl('canonical'));
    }
    else {
      $entity->delete();
      $form_state->setRedirectUrl($this->getRedirectUrl());
    }

    $this->messenger()->addStatus($message);
    $this->logDeletionMessage();
  }
$candidates = [];
        if (!empty($context['langcode'])) {
          $candidates[$context['langcode']] = $context['langcode'];
        }
        return $candidates;
      })
      ->shouldBeCalledTimes(1);

    $translated_entity = $this->prophesize(ContentEntityInterface::class);

    $entity = $this->prophesize(ContentEntityInterface::class);
    $entity->getUntranslated()->willReturn($entity);
    $entity->language()->willReturn($language);
    $entity->hasTranslation(LanguageInterface::LANGCODE_DEFAULT)->willReturn(FALSE);
    $entity->hasTranslation('custom_langcode')->willReturn(TRUE);
    $entity->getTranslation('custom_langcode')->willReturn($translated_entity->reveal());
    $entity->getTranslationLanguages()->willReturn([new Language(['id' => 'en'])new Language(['id' => 'custom_langcode'])]);
    $entity->addCacheContexts(['languages:language_content'])->shouldBeCalled();

    $this->assertSame($entity->reveal()$this->entityRepository->getTranslationFromContext($entity->reveal()));
    $this->assertSame($translated_entity->reveal()$this->entityRepository->getTranslationFromContext($entity->reveal(), 'custom_langcode'));
  }

}
$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()) {
      // Determine whether the current entity is translatable.

trait EntityChangedTrait {

  /** * Returns the timestamp of the last entity change across all translations. * * @return int * The timestamp of the last entity save operation across all * translations. */
  public function getChangedTimeAcrossTranslations() {
    $changed = $this->getUntranslated()->getChangedTime();
    foreach ($this->getTranslationLanguages(FALSE) as $language) {
      $translation_changed = $this->getTranslation($language->getId())->getChangedTime();
      $changed = max($translation_changed$changed);
    }
    return $changed;
  }

  /** * Gets the timestamp of the last entity change for the current translation. * * @return int|null * The timestamp of the last entity save operation. Some entities allow a * NULL value indicating the changed time is unknown. */
public function testRemovedTranslations() {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = EntityTestMulRev::create(['name' => 'Test 1.1 EN']);
    $this->storage->save($entity);

    /** @var \Drupal\Core\Entity\ContentEntityInterface $it_revision */
    $it_revision = $this->storage->createRevision($entity->addTranslation('it'));
    $it_revision->set('name', 'Test 1.2 IT');
    $this->storage->save($it_revision);

    /** @var \Drupal\Core\Entity\ContentEntityInterface $en_revision */
    $en_revision = $this->storage->createRevision($it_revision->getUntranslated(), FALSE);
    $en_revision->set('name', 'Test 1.3 EN');
    $this->storage->save($en_revision);

    /** @var \Drupal\Core\Entity\ContentEntityInterface $en_revision */
    $it_revision = $this->storage->createRevision($it_revision);
    $en_revision = $it_revision->getUntranslated();
    $en_revision->removeTranslation('it');
    $this->storage->save($en_revision);

    $revision_id = $this->storage->getLatestTranslationAffectedRevisionId($entity->id(), 'en');
    $en_revision = $this->storage->loadRevision($revision_id);
    
$entity->addCacheContexts(['languages:' . LanguageInterface::TYPE_CONTENT]);
      }

      // Retrieve language fallback candidates to perform the entity language       // negotiation, unless the current translation is already the desired one.       if ($entity->language()->getId() != $langcode) {
        $context['data'] = $entity;
        $context += ['operation' => 'entity_view', 'langcode' => $langcode];
        $candidates = $this->languageManager->getFallbackCandidates($context);

        // Ensure the default language has the proper language code.         $default_language = $entity->getUntranslated()->language();
        $candidates[$default_language->getId()] = LanguageInterface::LANGCODE_DEFAULT;

        // Return the most fitting entity translation.         foreach ($candidates as $candidate) {
          if ($entity->hasTranslation($candidate)) {
            $translation = $entity->getTranslation($candidate);
            break;
          }
        }
      }
    }

    

  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account$source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    if ($entity = $route_match->getParameter($entity_type_id)) {
      $operation = $route->getRequirement('_access_content_translation_manage');
      $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
      $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);

      if (in_array($operation['update', 'delete'])) {
        // Translation operations cannot be performed on the default         // translation.         if ($language->getId() == $entity->getUntranslated()->language()->getId()) {
          return AccessResult::forbidden()->addCacheableDependency($entity);
        }
        // Editors have no access to the translation operations, as entity         // access already grants them an equal or greater access level.         $templates = ['update' => 'edit-form', 'delete' => 'delete-form'];
        if ($entity->access($operation) && $entity_type->hasLinkTemplate($templates[$operation])) {
          return AccessResult::forbidden()->cachePerPermissions();
        }
      }

      if ($account->hasPermission('translate any entity')) {
        
public function getRevisionId() {
    return $this->getEntityKey('revision');
  }

  /** * {@inheritdoc} */
  public function isTranslatable() {
    // Check the bundle is translatable, the entity has a language defined, and     // the site has more than one language.     $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->entityTypeId);
    return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
  }

  /** * {@inheritdoc} */
  public function preSave(EntityStorageInterface $storage) {
    // An entity requiring validation should not be saved if it has not been     // actually validated.     assert(!$this->validationRequired || $this->validated, 'Entity validation was skipped.');

    $this->validated = FALSE;

    
$query = $this->database->delete('node_access')->condition('nid', $node->id());
      if ($realm) {
        $query->condition('realm', [$realm, 'all'], 'IN');
      }
      $query->execute();
    }
    // Only perform work when node_access modules are active.     if (!empty($grants) && $this->moduleHandler->hasImplementations('node_grants')) {
      $query = $this->database->insert('node_access')->fields(['nid', 'langcode', 'fallback', 'realm', 'gid', 'grant_view', 'grant_update', 'grant_delete']);
      // If we have defined a granted langcode, use it. But if not, add a grant       // for every language this node is translated to.       $fallback_langcode = $node->getUntranslated()->language()->getId();
      foreach ($grants as $grant) {
        if ($realm && $realm != $grant['realm']) {
          continue;
        }
        if (isset($grant['langcode'])) {
          $grant_languages = [$grant['langcode'] => $this->languageManager->getLanguage($grant['langcode'])];
        }
        else {
          $grant_languages = $node->getTranslationLanguages(TRUE);
        }
        foreach ($grant_languages as $grant_langcode => $grant_language) {
          

  public function syncUserLangcode($entity_type_id, UserInterface $user, array &$form, FormStateInterface &$form_state) {
    $user->getUntranslated()->langcode = $user->preferred_langcode;
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    // Change the roles array to a list of enabled roles.     // @todo Alter the form state as the form values are directly extracted and     // set on the field, which throws an exception as the list requires     // numeric keys. Allow to override this per field. As this function is     // called twice, we have to prevent it from getting the array keys twice.
->toString());
    }

    $items = [];
    $entities = $this->entityTypeManager->getStorage($entity_type_id)->loadMultiple(array_keys($this->selection));
    foreach ($this->selection as $id => $selected_langcodes) {
      $entity = $entities[$id];
      foreach ($selected_langcodes as $langcode) {
        $key = $id . ':' . $langcode;
        if ($entity instanceof TranslatableInterface) {
          $entity = $entity->getTranslation($langcode);
          $default_key = $id . ':' . $entity->getUntranslated()->language()->getId();

          // Build a nested list of translations that will be deleted if the           // entity has multiple translations.           $entity_languages = $entity->getTranslationLanguages();
          if (count($entity_languages) > 1 && $entity->isDefaultTranslation()) {
            $names = [];
            foreach ($entity_languages as $translation_langcode => $language) {
              $names[] = $language->getName();
              unset($items[$id . ':' . $translation_langcode]);
            }
            $items[$default_key] = [
              
Home | Imprint | This part of the site doesn't use cookies.