You are here

protected function ContentEntity::ensureTranslation in Commerce Core 8.2

Ensures the correct entity translation.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: The entity.

\Drupal\Core\Form\FormStateInterface $form_state: The form state.

Return value

\Drupal\Core\Entity\ContentEntityInterface The translated entity.

See also

\Drupal\Core\Entity\ContentEntityForm::initFormLangcodes()

1 call to ContentEntity::ensureTranslation()
ContentEntity::buildInlineForm in src/Plugin/Commerce/InlineForm/ContentEntity.php
Builds the inline form.

File

src/Plugin/Commerce/InlineForm/ContentEntity.php, line 134

Class

ContentEntity
Provides an inline form for managing a content entity.

Namespace

Drupal\commerce\Plugin\Commerce\InlineForm

Code

protected function ensureTranslation(ContentEntityInterface $entity, FormStateInterface $form_state) {
  $form_langcode = $form_state
    ->get('langcode');
  if (empty($form_langcode)) {

    // The top-level form is not a content entity form.
    return $entity;
  }
  $langcode_key = $this
    ->getLangcodeKey($entity);
  $entity_langcode = $entity
    ->get($langcode_key)->value;
  if ($this
    ->isTranslating($form_state) && !$entity
    ->hasTranslation($form_langcode)) {

    // Create a translation from the source language values.
    $source = $form_state
      ->get([
      'content_translation',
      'source',
    ]);
    $source_langcode = $source ? $source
      ->getId() : $entity_langcode;
    if (!$entity
      ->hasTranslation($source_langcode)) {
      $entity
        ->addTranslation($source_langcode, $entity
        ->toArray());
    }
    $source_translation = $entity
      ->getTranslation($source_langcode);
    $entity
      ->addTranslation($form_langcode, $source_translation
      ->toArray());
    $translation = $entity
      ->getTranslation($form_langcode);
    $translation
      ->set('content_translation_source', $source_langcode);

    // Make sure we do not inherit the affected status from the source values.
    if ($entity
      ->getEntityType()
      ->isRevisionable()) {
      $translation
        ->setRevisionTranslationAffected(NULL);
    }
  }
  if ($entity_langcode != $form_langcode && $entity
    ->hasTranslation($form_langcode)) {

    // Switch to the needed translation.
    $entity = $entity
      ->getTranslation($form_langcode);
  }
  return $entity;
}