function FieldItemNormalizer::createTranslatedInstance

Same name in other branches
  1. 9 core/modules/hal/src/Normalizer/FieldItemNormalizer.php \Drupal\hal\Normalizer\FieldItemNormalizer::createTranslatedInstance()

Get a translated version of the field item instance.

To indicate that a field item applies to one translation of an entity and not another, the property path must originate with a translation of the entity. This is the reason for using target_instances, from which the property path can be traversed up to the root.

Parameters

\Drupal\Core\Field\FieldItemInterface $item: The untranslated field item instance.

$langcode: The langcode.

Return value

\Drupal\Core\Field\FieldItemInterface The translated field item instance.

1 call to FieldItemNormalizer::createTranslatedInstance()
FieldItemNormalizer::denormalize in core/modules/hal/src/Normalizer/FieldItemNormalizer.php

File

core/modules/hal/src/Normalizer/FieldItemNormalizer.php, line 114

Class

FieldItemNormalizer
Converts the Drupal field item object structure to HAL array structure.

Namespace

Drupal\hal\Normalizer

Code

protected function createTranslatedInstance(FieldItemInterface $item, $langcode) {
    // Remove the untranslated item that was created for the default language
    // by FieldNormalizer::denormalize().
    $items = $item->getParent();
    $delta = $item->getName();
    unset($items[$delta]);
    // Instead, create a new item for the entity in the requested language.
    $entity = $item->getEntity();
    $entity_translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
    $field_name = $item->getFieldDefinition()
        ->getName();
    return $entity_translation->get($field_name)
        ->appendItem();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.