You are here

public function ContentEntityBase::addTranslation in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Entity/ContentEntityBase.php \Drupal\Core\Entity\ContentEntityBase::addTranslation()
  2. 10 core/lib/Drupal/Core/Entity/ContentEntityBase.php \Drupal\Core\Entity\ContentEntityBase::addTranslation()

Adds a new translation to the translatable object.

To create a translation of an entity prefilled with the original data:

$entity
  ->addTranslation($langcode, $entity
  ->toArray());

Parameters

string $langcode: The language code identifying the translation.

array $values: (optional) An array of initial values to be assigned to the translatable fields. Defaults to none.

Return value

$this

Throws

\InvalidArgumentException If an invalid or existing translation language is specified.

Overrides TranslatableInterface::addTranslation

File

core/lib/Drupal/Core/Entity/ContentEntityBase.php, line 950

Class

ContentEntityBase
Implements Entity Field API specific enhancements to the Entity class.

Namespace

Drupal\Core\Entity

Code

public function addTranslation($langcode, array $values = []) {

  // Make sure we do not attempt to create a translation if an invalid
  // language is specified or the entity cannot be translated.
  $this
    ->getLanguages();
  if (!isset($this->languages[$langcode]) || $this
    ->hasTranslation($langcode) || $this->languages[$langcode]
    ->isLocked()) {
    throw new \InvalidArgumentException("Invalid translation language ({$langcode}) specified.");
  }
  if ($this->languages[$this->defaultLangcode]
    ->isLocked()) {
    throw new \InvalidArgumentException("The entity cannot be translated since it is language neutral ({$this->defaultLangcode}).");
  }

  // Initialize the translation object.

  /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
  $storage = $this
    ->entityTypeManager()
    ->getStorage($this
    ->getEntityTypeId());
  $this->translations[$langcode]['status'] = !isset($this->translations[$langcode]['status_existed']) ? static::TRANSLATION_CREATED : static::TRANSLATION_EXISTING;
  return $storage
    ->createTranslation($this, $langcode, $values);
}