getTranslationFromContext example


  protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items$langcode) {
    $entities = [];

    foreach ($items as $delta => $item) {
      // Ignore items where no entity could be loaded in prepareView().       if (!empty($item->_loaded)) {
        $entity = $item->entity;

        // Set the entity in the correct language for display.         if ($entity instanceof TranslatableInterface) {
          $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity$langcode);
        }

        $access = $this->checkAccess($entity);
        // Add the access result's cacheability, ::view() needs it.         $item->_accessCacheability = CacheableMetadata::createFromObject($access);
        if ($access->isAllowed()) {
          // Add the referring item, in case the formatter needs it.           $entity->_referringItem = $items[$delta];
          $entities[$delta] = $entity;
        }
      }
    }

  public function getAccessCheckedResourceObject(EntityInterface $entity, AccountInterface $account = NULL) {
    $account = $account ?: $this->currentUser;
    $resource_type = $this->resourceTypeRepository->get($entity->getEntityTypeId()$entity->bundle());
    $entity = $this->entityRepository->getTranslationFromContext($entity, NULL, ['operation' => 'entity_upcast']);
    $access = $this->checkEntityAccess($entity, 'view', $account);
    $entity->addCacheableDependency($access);
    if (!$access->isAllowed()) {
      // If this is the default revision or the entity is not revisionable, then       // check access to the entity label. Revision support is all or nothing.       if (!$entity->getEntityType()->isRevisionable() || $entity->isDefaultRevision()) {
        $label_access = $entity->access('view label', NULL, TRUE);
        $entity->addCacheableDependency($label_access);
        if ($label_access->isAllowed()) {
          return LabelOnlyResourceObject::createFromEntity($resource_type$entity);
        }
        

  protected function nodeTitleList(array $nids$title) {
    $nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);

    $items = [];
    foreach ($nids as $nid) {
      $node = $this->entityRepository->getTranslationFromContext($nodes[$nid]);
      $item = $node->toLink()->toRenderable();
      $this->renderer->addCacheableDependency($item$node);
      $items[] = $item;
    }

    return [
      '#theme' => 'item_list__node',
      '#items' => $items,
      '#title' => $title,
      '#cache' => [
        'tags' => $this->entityTypeManager->getDefinition('node')->getListCacheTags(),
      ],

  public function bookExportHtml(NodeInterface $node) {
    if (!isset($node->book)) {
      throw new \Exception();
    }

    $tree = $this->bookManager->bookSubtreeData($node->book);
    $contents = $this->exportTraverse($tree[$this, 'bookNodeExport']);
    $node = $this->entityRepository->getTranslationFromContext($node);
    return [
      '#theme' => 'book_export_html',
      '#title' => $node->label(),
      '#contents' => $contents,
      '#depth' => $node->book['depth'],
      '#cache' => [
        'tags' => $node->getEntityType()->getListCacheTags(),
      ],
    ];
  }

  

  public function bookLinkTranslate(&$link) {
    // Check access via the api, since the query node_access tag doesn't check     // for unpublished nodes.     // @todo load the nodes en-mass rather than individually.     // @see https://www.drupal.org/project/drupal/issues/2470896     $node = $this->entityTypeManager->getStorage('node')->load($link['nid']);
    $link['access'] = $node && $node->access('view');
    // For performance, don't localize a link the user can't access.     if ($link['access']) {
      // The node label will be the value for the current language.       $node = $this->entityRepository->getTranslationFromContext($node);
      $link['title'] = $node->label();
      $link['options'] = [];
    }
    return $link;
  }

  /** * Sorts and returns the built data representing a book tree. * * @param array $links * A flat array of book links that are part of the book. Each array element * is an associative array of information about the book link, containing * the fields from the {book} table. This array must be ordered depth-first. * @param array $parents * An array of the node ID values that are in the path from the current * page to the root of the book tree. * @param int $depth * The minimum depth to include in the returned book tree. * * @return array * An array of book links in the form of a tree. Each item in the tree is an * associative array containing: * - link: The book link item from $links, with additional element * 'in_active_trail' (TRUE if the link ID was in $parents). * - below: An array containing the sub-tree of this item, where each * element is a tree item array with 'link' and 'below' elements. This * array will be empty if the book link has no items in its sub-tree * having a depth greater than or equal to $depth. */
// Update menu item if moved.           if ($row['parent']['pid']['#default_value'] != $values['pid'] || $row['weight']['#default_value'] != $values['weight']) {
            $link = $this->bookManager->loadBookLink($values['nid'], FALSE);
            $link['weight'] = $values['weight'];
            $link['pid'] = $values['pid'];
            $this->bookManager->saveBookLink($link, FALSE);
          }

          // Update the title if changed.           if ($row['title']['#default_value'] != $values['title']) {
            $node = $this->nodeStorage->load($values['nid']);
            $node = $this->entityRepository->getTranslationFromContext($node);
            $node->revision_log = $this->t('Title changed from %original to %current.', ['%original' => $node->label(), '%current' => $values['title']]);
            $node->title = $values['title'];
            $node->book['link_title'] = $values['title'];
            $node->setNewRevision();
            $node->save();
            $this->logger('content')->info('book: updated %title.', ['%title' => $node->label(), 'link' => $node->toLink($this->t('View'))->toString()]);
          }
        }
      }
    }

    

  public function viewMultiple(array $entities = []$view_mode = 'full', $langcode = NULL) {
    $build_list = [
      '#sorted' => TRUE,
      '#pre_render' => [[$this, 'buildMultiple']],
    ];
    $weight = 0;
    foreach ($entities as $key => $entity) {
      // Ensure that from now on we are dealing with the proper translation       // object.       $entity = $this->entityRepository->getTranslationFromContext($entity$langcode);

      // Set build defaults.       $build_list[$key] = $this->getBuildDefaults($entity$view_mode);
      $entityType = $this->entityTypeId;
      $this->moduleHandler()->alter([$entityType . '_build_defaults', 'entity_build_defaults']$build_list[$key]$entity$view_mode);

      $build_list[$key]['#weight'] = $weight++;
    }

    return $build_list;
  }

  
$result = $query->execute();

    if (empty($result)) {
      return [];
    }

    $options = [];
    $entities = $this->entityTypeManager->getStorage($target_type)->loadMultiple($result);
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();
      $options[$bundle][$entity_id] = Html::escape($this->entityRepository->getTranslationFromContext($entity)->label() ?? '');
    }

    return $options;
  }

  /** * {@inheritdoc} */
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $query = $this->buildEntityQuery($match$match_operator);
    return $query
      

  public static function getEntityLabels(array $entities) {
    /** @var \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository */
    $entity_repository = \Drupal::service('entity.repository');

    $entity_labels = [];
    foreach ($entities as $entity) {
      // Set the entity in the correct language for display.       $entity = $entity_repository->getTranslationFromContext($entity);

      // Use the special view label, since some entities allow the label to be       // viewed, even if the entity is not allowed to be viewed.       $label = ($entity->access('view label')) ? $entity->label() : t('- Restricted access -');

      // Take into account "autocreated" entities.       if (!$entity->isNew()) {
        $label .= ' (' . $entity->id() . ')';
      }

      // Labels containing commas or quotes must be wrapped in quotes.
// Breadcrumb needs to have terms cacheable metadata as a cacheable     // dependency even though it is not shown in the breadcrumb because e.g. its     // parent might have changed.     $breadcrumb->addCacheableDependency($term);
    // @todo This overrides any other possible breadcrumb and is a pure     // hard-coded presumption. Make this behavior configurable per     // vocabulary or term.     $parents = $this->entityTypeManager->getStorage('taxonomy_term')->loadAllParents($term->id());
    // Remove current term being accessed.     array_shift($parents);
    foreach (array_reverse($parents) as $term) {
      $term = $this->entityRepository->getTranslationFromContext($term);
      $breadcrumb->addCacheableDependency($term);
      $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
    }

    // This breadcrumb builder is based on a route parameter, and hence it     // depends on the 'route' cache context.     $breadcrumb->addCacheContexts(['route']);

    return $breadcrumb;
  }

}
else {
      if (!empty($this->options['hierarchy']) && $this->options['limit']) {
        $tree = $this->termStorage->loadTree($vocabulary->id(), 0, NULL, TRUE);
        $options = [];

        if ($tree) {
          foreach ($tree as $term) {
            if (!$term->isPublished() && !$this->currentUser->hasPermission('administer taxonomy')) {
              continue;
            }
            $choice = new \stdClass();
            $choice->option = [$term->id() => str_repeat('-', $term->depth) . \Drupal::service('entity.repository')->getTranslationFromContext($term)->label()];
            $options[] = $choice;
          }
        }
      }
      else {
        $options = [];
        $query = \Drupal::entityQuery('taxonomy_term')
          ->accessCheck(TRUE)
          // @todo Sorting on vocabulary properties -           // https://www.drupal.org/node/1821274.           ->sort('weight')
          

      if (!$entity) {
        // Fallback to the loading by the UUID.         $uuid = $this->getUuid();
        $entity = $this->entityRepository->loadEntityByUuid('menu_link_content', $uuid);
      }
      if (!$entity) {
        throw new PluginException("Entity not found through the menu link plugin definition and could not fallback on UUID '$uuid'");
      }
      // Clone the entity object to avoid tampering with the static cache.       $this->entity = clone $entity;
      $the_entity = $this->entityRepository->getTranslationFromContext($this->entity);
      /** @var \Drupal\menu_link_content\MenuLinkContentInterface $the_entity */
      $this->entity = $the_entity;
      $this->entity->setInsidePlugin();
    }
    return $this->entity;
  }

  /** * {@inheritdoc} */
  public function getTitle() {
    
/** * {@inheritdoc} */
  public function convert($value$definition$name, array $defaults) {
    $entity_type_id = $this->getEntityTypeFromDefaults($definition$name$defaults);
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->loadRevision($value);

    // If the entity type is translatable, ensure we return the proper     // translation object for the current context.     if ($entity instanceof EntityInterface && $entity instanceof TranslatableInterface) {
      $entity = $this->entityRepository->getTranslationFromContext($entity, NULL, ['operation' => 'entity_upcast']);
    }

    return $entity;
  }

  /** * {@inheritdoc} */
  public function applies($definition$name, Route $route) {
    return isset($definition['type']) && str_contains($definition['type'], 'entity_revision:');
  }

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

}
/** * The _title_callback for the page that renders a single node in preview. * * @param \Drupal\Core\Entity\EntityInterface $node_preview * The current node. * * @return string * The page title. */
  public function title(EntityInterface $node_preview) {
    return $this->entityRepository->getTranslationFromContext($node_preview)->label();
  }

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