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.
\Drupal\Core\Entity\Field\FieldItemInterface $field_item: The untranslated field item instance.
$langcode: The langcode.
\Drupal\Core\Entity\Field\FieldItemInterface The translated field item instance.
protected function createTranslatedInstance(FieldItemInterface $field_item, $langcode) {
$parent = $field_item
->getParent();
$ancestors = array();
// Remove the untranslated instance from the field's list of items.
$parent
->offsetUnset($field_item
->getName());
// Get the property path.
while (!method_exists($parent, 'getTranslation')) {
array_unshift($ancestors, $parent);
$parent = $parent
->getParent();
}
// Recreate the property path with translations.
$translation = $parent
->getTranslation($langcode);
foreach ($ancestors as $ancestor) {
$ancestor_name = $ancestor
->getName();
$translation = $translation
->get($ancestor_name);
}
// Create a new instance at the end of the property path and return it.
$count = $translation
->isEmpty() ? 0 : $translation
->count();
return $translation
->offsetGet($count);
}