예제 #1
0
 /**
  * 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.
  *
  * @param \Drupal\Core\Field\FieldItemInterface $field_item
  *   The untranslated field item instance.
  * @param $langcode
  *   The langcode.
  *
  * @return \Drupal\Core\Field\FieldItemInterface
  *   The translated field item instance.
  */
 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();
 }
 /**
  * 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.
  *
  * @param \Drupal\Core\Field\FieldItemInterface $field_item
  *   The untranslated field item instance.
  * @param $langcode
  *   The langcode.
  *
  * @return \Drupal\Core\Field\FieldItemInterface
  *   The translated field item instance.
  */
 protected function createTranslatedInstance(FieldItemInterface $field_item, $langcode)
 {
     $field_items = $field_item->getParent();
     // Remove the untranslated instance from the field's list of items.
     $field_items->offsetUnset($field_item->getName());
     // Get the entity in the requested language and the field's item list from
     // that.
     $entity_translation = $field_item->getEntity()->getTranslation($langcode);
     $field_items_translation = $entity_translation->get($field_item->getFieldDefinition()->getName());
     // Create a new instance and return it.
     $count = $field_items_translation->isEmpty() ? 0 : $field_items_translation->count();
     return $field_items_translation->get($count);
 }