3 namespace Drupal\content_translation;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
7 use Drupal\Core\Entity\EntityChangedInterface;
8 use Drupal\Core\Entity\EntityChangesDetectionTrait;
9 use Drupal\Core\Entity\EntityHandlerInterface;
10 use Drupal\Core\Entity\EntityInterface;
11 use Drupal\Core\Entity\EntityManagerInterface;
12 use Drupal\Core\Entity\EntityTypeInterface;
13 use Drupal\Core\Field\BaseFieldDefinition;
14 use Drupal\Core\Form\FormStateInterface;
15 use Drupal\Core\Language\LanguageInterface;
16 use Drupal\Core\Language\LanguageManagerInterface;
17 use Drupal\Core\Messenger\MessengerInterface;
18 use Drupal\Core\Render\Element;
19 use Drupal\Core\Session\AccountInterface;
20 use Drupal\Core\StringTranslation\StringTranslationTrait;
21 use Drupal\user\Entity\User;
22 use Drupal\user\EntityOwnerInterface;
23 use Symfony\Component\DependencyInjection\ContainerInterface;
26 * Base class for content translation handlers.
30 class ContentTranslationHandler implements ContentTranslationHandlerInterface, EntityHandlerInterface {
32 use EntityChangesDetectionTrait;
33 use DependencySerializationTrait;
34 use StringTranslationTrait;
37 * The type of the entity being translated.
41 protected $entityTypeId;
44 * Information about the entity type.
46 * @var \Drupal\Core\Entity\EntityTypeInterface
48 protected $entityType;
51 * The language manager.
53 * @var \Drupal\Core\Language\LanguageManagerInterface
55 protected $languageManager;
58 * The content translation manager.
60 * @var \Drupal\content_translation\ContentTranslationManagerInterface
65 * The entity type manager.
67 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
69 protected $entityTypeManager;
74 * @var \Drupal\Core\Session\AccountInterface
76 protected $currentUser;
79 * The array of installed field storage definitions for the entity type, keyed
82 * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
84 protected $fieldStorageDefinitions;
87 * The messenger service.
89 * @var \Drupal\Core\Messenger\MessengerInterface
94 * Initializes an instance of the content translation controller.
96 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
97 * The info array of the given entity type.
98 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
99 * The language manager.
100 * @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
101 * The content translation manager service.
102 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
103 * The entity manager.
104 * @param \Drupal\Core\Session\AccountInterface $current_user
106 * @param \Drupal\Core\Messenger\MessengerInterface $messenger
107 * The messenger service.
109 public function __construct(EntityTypeInterface $entity_type, LanguageManagerInterface $language_manager, ContentTranslationManagerInterface $manager, EntityManagerInterface $entity_manager, AccountInterface $current_user, MessengerInterface $messenger) {
110 $this->entityTypeId = $entity_type->id();
111 $this->entityType = $entity_type;
112 $this->languageManager = $language_manager;
113 $this->manager = $manager;
114 $this->entityTypeManager = $entity_manager;
115 $this->currentUser = $current_user;
116 $this->fieldStorageDefinitions = $entity_manager->getLastInstalledFieldStorageDefinitions($this->entityTypeId);
117 $this->messenger = $messenger;
123 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
126 $container->get('language_manager'),
127 $container->get('content_translation.manager'),
128 $container->get('entity.manager'),
129 $container->get('current_user'),
130 $container->get('messenger')
137 public function getFieldDefinitions() {
140 $definitions['content_translation_source'] = BaseFieldDefinition::create('language')
141 ->setLabel(t('Translation source'))
142 ->setDescription(t('The source language from which this translation was created.'))
143 ->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
144 ->setInitialValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
145 ->setRevisionable(TRUE)
146 ->setTranslatable(TRUE);
148 $definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
149 ->setLabel(t('Translation outdated'))
150 ->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
151 ->setDefaultValue(FALSE)
152 ->setInitialValue(FALSE)
153 ->setRevisionable(TRUE)
154 ->setTranslatable(TRUE);
156 if (!$this->hasAuthor()) {
157 $definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
158 ->setLabel(t('Translation author'))
159 ->setDescription(t('The author of this translation.'))
160 ->setSetting('target_type', 'user')
161 ->setSetting('handler', 'default')
162 ->setRevisionable(TRUE)
163 ->setDefaultValueCallback(get_class($this) . '::getDefaultOwnerId')
164 ->setTranslatable(TRUE);
167 if (!$this->hasPublishedStatus()) {
168 $definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
169 ->setLabel(t('Translation status'))
170 ->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
171 ->setDefaultValue(TRUE)
172 ->setInitialValue(TRUE)
173 ->setRevisionable(TRUE)
174 ->setTranslatable(TRUE);
177 if (!$this->hasCreatedTime()) {
178 $definitions['content_translation_created'] = BaseFieldDefinition::create('created')
179 ->setLabel(t('Translation created time'))
180 ->setDescription(t('The Unix timestamp when the translation was created.'))
181 ->setRevisionable(TRUE)
182 ->setTranslatable(TRUE);
185 if (!$this->hasChangedTime()) {
186 $definitions['content_translation_changed'] = BaseFieldDefinition::create('changed')
187 ->setLabel(t('Translation changed time'))
188 ->setDescription(t('The Unix timestamp when the translation was most recently saved.'))
189 ->setRevisionable(TRUE)
190 ->setTranslatable(TRUE);
197 * Checks whether the entity type supports author natively.
200 * TRUE if metadata is natively supported, FALSE otherwise.
202 protected function hasAuthor() {
203 // Check for field named uid, but only in case the entity implements the
204 // EntityOwnerInterface. This helps to exclude cases, where the uid is
205 // defined as field name, but is not meant to be an owner field; for
206 // instance, the User entity.
207 return $this->entityType->entityClassImplements(EntityOwnerInterface::class) && $this->checkFieldStorageDefinitionTranslatability('uid');
211 * Checks whether the entity type supports published status natively.
214 * TRUE if metadata is natively supported, FALSE otherwise.
216 protected function hasPublishedStatus() {
217 return $this->checkFieldStorageDefinitionTranslatability('status');
221 * Checks whether the entity type supports modification time natively.
224 * TRUE if metadata is natively supported, FALSE otherwise.
226 protected function hasChangedTime() {
227 return $this->entityType->entityClassImplements(EntityChangedInterface::class) && $this->checkFieldStorageDefinitionTranslatability('changed');
231 * Checks whether the entity type supports creation time natively.
234 * TRUE if metadata is natively supported, FALSE otherwise.
236 protected function hasCreatedTime() {
237 return $this->checkFieldStorageDefinitionTranslatability('created');
241 * Checks the field storage definition for translatability support.
243 * Checks whether the given field is defined in the field storage definitions
244 * and if its definition specifies it as translatable.
246 * @param string $field_name
247 * The name of the field.
250 * TRUE if translatable field storage definition exists, FALSE otherwise.
252 protected function checkFieldStorageDefinitionTranslatability($field_name) {
253 return array_key_exists($field_name, $this->fieldStorageDefinitions) && $this->fieldStorageDefinitions[$field_name]->isTranslatable();
259 public function retranslate(EntityInterface $entity, $langcode = NULL) {
260 $updated_langcode = !empty($langcode) ? $langcode : $entity->language()->getId();
261 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
262 $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
263 ->setOutdated($langcode != $updated_langcode);
270 public function getTranslationAccess(EntityInterface $entity, $op) {
271 // @todo Move this logic into a translation access control handler checking also
272 // the translation language and the given account.
273 $entity_type = $entity->getEntityType();
274 $translate_permission = TRUE;
275 // If no permission granularity is defined this entity type does not need an
276 // explicit translate permission.
277 if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
278 $translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
280 return AccessResult::allowedIf($translate_permission && $this->currentUser->hasPermission("$op content translations"))->cachePerPermissions();
286 public function getSourceLangcode(FormStateInterface $form_state) {
287 if ($source = $form_state->get(['content_translation', 'source'])) {
288 return $source->getId();
296 public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
297 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
299 $form_object = $form_state->getFormObject();
300 $form_langcode = $form_object->getFormLangcode($form_state);
301 $entity_langcode = $entity->getUntranslated()->language()->getId();
302 $source_langcode = $this->getSourceLangcode($form_state);
304 $new_translation = !empty($source_langcode);
305 $translations = $entity->getTranslationLanguages();
306 if ($new_translation) {
307 // Make sure a new translation does not appear as existing yet.
308 unset($translations[$form_langcode]);
310 $is_translation = !$form_object->isDefaultFormLangcode($form_state);
311 $has_translations = count($translations) > 1;
313 // Adjust page title to specify the current language being edited, if we
314 // have at least one translation.
315 $languages = $this->languageManager->getLanguages();
316 if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
317 $title = $this->entityFormTitle($entity);
318 // When editing the original values display just the entity label.
319 if ($is_translation) {
320 $t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title];
321 $title = empty($source_langcode) ? t('@title [%language translation]', $t_args) : t('Create %language translation of %title', $t_args);
323 $form['#title'] = $title;
326 // Display source language selector only if we are creating a new
327 // translation and there are at least two translations available.
328 if ($has_translations && $new_translation) {
329 $form['source_langcode'] = [
330 '#type' => 'details',
331 '#title' => t('Source language: @language', ['@language' => $languages[$source_langcode]->getName()]),
334 '#multilingual' => TRUE,
336 '#title' => t('Select source language'),
337 '#title_display' => 'invisible',
339 '#default_value' => $source_langcode,
344 '#value' => t('Change'),
345 '#submit' => [[$this, 'entityFormSourceChange']],
348 foreach ($this->languageManager->getLanguages() as $language) {
349 if (isset($translations[$language->getId()])) {
350 $form['source_langcode']['source']['#options'][$language->getId()] = $language->getName();
355 // Locate the language widget.
356 $langcode_key = $this->entityType->getKey('langcode');
357 if (isset($form[$langcode_key])) {
358 $language_widget = &$form[$langcode_key];
361 // If we are editing the source entity, limit the list of languages so that
362 // it is not possible to switch to a language for which a translation
363 // already exists. Note that this will only work if the widget is structured
364 // like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
365 if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
366 $language_select = &$language_widget['widget'][0]['value'];
367 if ($language_select['#type'] == 'language_select') {
369 foreach ($this->languageManager->getLanguages() as $language) {
370 // Show the current language, and the languages for which no
371 // translation already exists.
372 if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
373 $options[$language->getId()] = $language->getName();
376 $language_select['#options'] = $options;
379 if ($is_translation) {
380 if (isset($language_widget)) {
381 $language_widget['widget']['#access'] = FALSE;
384 // Replace the delete button with the delete translation one.
385 if (!$new_translation) {
387 foreach (['delete', 'submit'] as $key) {
388 if (isset($form['actions'][$key]['weight'])) {
389 $weight = $form['actions'][$key]['weight'];
393 /** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
394 $delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
395 $access = $delete_access->isAllowed() && (
396 $this->getTranslationAccess($entity, 'delete')->isAllowed() ||
397 ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form'))
399 $form['actions']['delete_translation'] = [
401 '#value' => t('Delete translation'),
402 '#weight' => $weight,
403 '#submit' => [[$this, 'entityFormDeleteTranslation']],
404 '#access' => $access,
408 // Always remove the delete button on translation forms.
409 unset($form['actions']['delete']);
412 // We need to display the translation tab only when there is at least one
413 // translation available or a new one is about to be created.
414 if ($new_translation || $has_translations) {
415 $form['content_translation'] = [
416 '#type' => 'details',
417 '#title' => t('Translation'),
420 '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update')->isAllowed(),
421 '#multilingual' => TRUE,
424 if (isset($form['advanced'])) {
425 $form['content_translation'] += [
426 '#group' => 'advanced',
429 'class' => ['entity-translation-options'],
434 // A new translation is enabled by default.
435 $metadata = $this->manager->getTranslationMetadata($entity);
436 $status = $new_translation || $metadata->isPublished();
437 // If there is only one published translation we cannot unpublish it,
438 // since there would be nothing left to display.
442 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
443 $published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
446 $enabled = $published > 1;
448 $description = $enabled ?
449 t('An unpublished translation will not be visible without translation permissions.') :
450 t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
452 $form['content_translation']['status'] = [
453 '#type' => 'checkbox',
454 '#title' => t('This translation is published'),
455 '#default_value' => $status,
456 '#description' => $description,
457 '#disabled' => !$enabled,
460 $translate = !$new_translation && $metadata->isOutdated();
461 $outdated_access = !ContentTranslationManager::isPendingRevisionSupportEnabled($entity->getEntityTypeId(), $entity->bundle());
462 if (!$outdated_access) {
463 $form['content_translation']['outdated'] = [
464 '#markup' => $this->t('Translations cannot be flagged as outdated when content is moderated.'),
467 elseif (!$translate) {
468 $form['content_translation']['retranslate'] = [
469 '#type' => 'checkbox',
470 '#title' => t('Flag other translations as outdated'),
471 '#default_value' => FALSE,
472 '#description' => t('If you made a significant change, which means the other translations should be updated, you can flag all translations of this content as outdated. This will not change any other property of them, like whether they are published or not.'),
473 '#access' => $outdated_access,
477 $form['content_translation']['outdated'] = [
478 '#type' => 'checkbox',
479 '#title' => t('This translation needs to be updated'),
480 '#default_value' => $translate,
481 '#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'),
482 '#access' => $outdated_access,
484 $form['content_translation']['#open'] = TRUE;
487 // Default to the anonymous user.
489 if ($new_translation) {
490 $uid = $this->currentUser->id();
492 elseif (($account = $metadata->getAuthor()) && $account->id()) {
493 $uid = $account->id();
495 $form['content_translation']['uid'] = [
496 '#type' => 'entity_autocomplete',
497 '#title' => t('Authored by'),
498 '#target_type' => 'user',
499 '#default_value' => User::load($uid),
500 // Validation is done by static::entityFormValidate().
501 '#validate_reference' => FALSE,
503 '#description' => t('Leave blank for %anonymous.', ['%anonymous' => \Drupal::config('user.settings')->get('anonymous')]),
506 $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime();
507 $form['content_translation']['created'] = [
508 '#type' => 'textfield',
509 '#title' => t('Authored on'),
511 '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', ['%time' => format_date(REQUEST_TIME, 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date(REQUEST_TIME, 'custom', 'O')]),
512 '#default_value' => $new_translation || !$date ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'),
515 $form['#process'][] = [$this, 'entityFormSharedElements'];
518 // Process the submitted values before they are stored.
519 $form['#entity_builders'][] = [$this, 'entityFormEntityBuild'];
521 // Handle entity validation.
522 $form['#validate'][] = [$this, 'entityFormValidate'];
524 // Handle entity deletion.
525 if (isset($form['actions']['delete'])) {
526 $form['actions']['delete']['#submit'][] = [$this, 'entityFormDelete'];
529 // Handle entity form submission before the entity has been saved.
530 foreach (Element::children($form['actions']) as $action) {
531 if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
532 array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
538 * Process callback: determines which elements get clue in the form.
540 * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
542 public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
543 static $ignored_types;
545 // @todo Find a more reliable way to determine if a form element concerns a
546 // multilingual value.
547 if (!isset($ignored_types)) {
548 $ignored_types = array_flip(['actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details']);
551 /** @var \Drupal\Core\Entity\ContentEntityForm $form_object */
552 $form_object = $form_state->getFormObject();
553 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
554 $entity = $form_object->getEntity();
555 $display_translatability_clue = !$entity->isDefaultTranslationAffectedOnly();
556 $hide_untranslatable_fields = $entity->isDefaultTranslationAffectedOnly() && !$entity->isDefaultTranslation();
557 $translation_form = $form_state->get(['content_translation', 'translation_form']);
558 $display_warning = FALSE;
560 // We use field definitions to identify untranslatable field widgets to be
561 // hidden. Fields that are not involved in translation changes checks should
562 // not be affected by this logic (the "revision_log" field, for instance).
563 $field_definitions = array_diff_key($entity->getFieldDefinitions(), array_flip($this->getFieldsToSkipFromTranslationChangesCheck($entity)));
565 foreach (Element::children($element) as $key) {
566 if (!isset($element[$key]['#type'])) {
567 $this->entityFormSharedElements($element[$key], $form_state, $form);
570 // Ignore non-widget form elements.
571 if (isset($ignored_types[$element[$key]['#type']])) {
574 // Elements are considered to be non multilingual by default.
575 if (empty($element[$key]['#multilingual'])) {
576 // If we are displaying a multilingual entity form we need to provide
577 // translatability clues, otherwise the non-multilingual form elements
579 if (!$translation_form) {
580 if ($display_translatability_clue) {
581 $this->addTranslatabilityClue($element[$key]);
583 // Hide widgets for untranslatable fields.
584 if ($hide_untranslatable_fields && isset($field_definitions[$key])) {
585 $element[$key]['#access'] = FALSE;
586 $display_warning = TRUE;
590 $element[$key]['#access'] = FALSE;
596 if ($display_warning && !$form_state->isSubmitted() && !$form_state->isRebuilding()) {
597 $url = $entity->getUntranslated()->toUrl('edit-form')->toString();
598 $this->messenger->addWarning($this->t('Fields that apply to all languages are hidden to avoid conflicting changes. <a href=":url">Edit them on the original language form</a>.', [':url' => $url]));
605 * Adds a clue about the form element translatability.
607 * If the given element does not have a #title attribute, the function is
608 * recursively applied to child elements.
610 * @param array $element
611 * A form element array.
613 protected function addTranslatabilityClue(&$element) {
614 static $suffix, $fapi_title_elements;
616 // Elements which can have a #title attribute according to FAPI Reference.
617 if (!isset($suffix)) {
618 $suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
619 $fapi_title_elements = array_flip(['checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight']);
622 // Update #title attribute for all elements that are allowed to have a
623 // #title attribute according to the Form API Reference. The reason for this
624 // check is because some elements have a #title attribute even though it is
625 // not rendered; for instance, field containers.
626 if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
627 $element['#title'] .= $suffix;
629 // If the current element does not have a (valid) title, try child elements.
630 elseif ($children = Element::children($element)) {
631 foreach ($children as $delta) {
632 $this->addTranslatabilityClue($element[$delta], $suffix);
635 // If there are no children, fall back to the current #title attribute if it
637 elseif (isset($element['#title'])) {
638 $element['#title'] .= $suffix;
643 * Entity builder method.
645 * @param string $entity_type
646 * The type of the entity.
647 * @param \Drupal\Core\Entity\EntityInterface $entity
648 * The entity whose form is being built.
650 * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
652 public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
653 $form_object = $form_state->getFormObject();
654 $form_langcode = $form_object->getFormLangcode($form_state);
655 $values = &$form_state->getValue('content_translation', []);
657 $metadata = $this->manager->getTranslationMetadata($entity);
658 $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
659 $metadata->setPublished(!empty($values['status']));
660 $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME);
662 $source_langcode = $this->getSourceLangcode($form_state);
663 if ($source_langcode) {
664 $metadata->setSource($source_langcode);
667 $metadata->setOutdated(!empty($values['outdated']));
668 if (!empty($values['retranslate'])) {
669 $this->retranslate($entity, $form_langcode);
674 * Form validation handler for ContentTranslationHandler::entityFormAlter().
676 * Validates the submitted content translation metadata.
678 public function entityFormValidate($form, FormStateInterface $form_state) {
679 if (!$form_state->isValueEmpty('content_translation')) {
680 $translation = $form_state->getValue('content_translation');
681 // Validate the "authored by" field.
682 if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
683 $form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', ['%name' => $account->getUsername()]));
685 // Validate the "authored on" field.
686 if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
687 $form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
693 * Form submission handler for ContentTranslationHandler::entityFormAlter().
695 * Updates metadata fields, which should be updated only after the validation
696 * has run and before the entity is saved.
698 public function entityFormSubmit($form, FormStateInterface $form_state) {
699 /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
700 $form_object = $form_state->getFormObject();
701 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
702 $entity = $form_object->getEntity();
704 // ContentEntityForm::submit will update the changed timestamp on submit
705 // after the entity has been validated, so that it does not break the
706 // EntityChanged constraint validator. The content translation metadata
707 // field for the changed timestamp does not have such a constraint defined
708 // at the moment, but it is correct to update its value in a submission
709 // handler as well and have the same logic like in the Form API.
710 if ($entity->hasField('content_translation_changed')) {
711 $metadata = $this->manager->getTranslationMetadata($entity);
712 $metadata->setChangedTime(REQUEST_TIME);
717 * Form submission handler for ContentTranslationHandler::entityFormAlter().
719 * Takes care of the source language change.
721 public function entityFormSourceChange($form, FormStateInterface $form_state) {
722 $form_object = $form_state->getFormObject();
723 $entity = $form_object->getEntity();
724 $source = $form_state->getValue(['source_langcode', 'source']);
726 $entity_type_id = $entity->getEntityTypeId();
727 $form_state->setRedirect("entity.$entity_type_id.content_translation_add", [
728 $entity_type_id => $entity->id(),
730 'target' => $form_object->getFormLangcode($form_state),
732 $languages = $this->languageManager->getLanguages();
733 $this->messenger->addStatus(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
737 * Form submission handler for ContentTranslationHandler::entityFormAlter().
739 * Takes care of entity deletion.
741 public function entityFormDelete($form, FormStateInterface $form_state) {
742 $form_object = $form_state->getFormObject();
743 $entity = $form_object->getEntity();
744 if (count($entity->getTranslationLanguages()) > 1) {
745 $this->messenger->addWarning(t('This will delete all the translations of %label.', ['%label' => $entity->label()]));
750 * Form submission handler for ContentTranslationHandler::entityFormAlter().
752 * Takes care of content translation deletion.
754 public function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
755 /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
756 $form_object = $form_state->getFormObject();
757 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
758 $entity = $form_object->getEntity();
759 $entity_type_id = $entity->getEntityTypeId();
760 if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
761 $form_state->setRedirectUrl($entity->urlInfo('delete-form'));
764 $form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
765 $entity_type_id => $entity->id(),
766 'language' => $form_object->getFormLangcode($form_state),
772 * Returns the title to be used for the entity form page.
774 * @param \Drupal\Core\Entity\EntityInterface $entity
775 * The entity whose form is being altered.
777 * @return string|null
778 * The label of the entity, or NULL if there is no label defined.
780 protected function entityFormTitle(EntityInterface $entity) {
781 return $entity->label();
785 * Default value callback for the owner base field definition.
790 public static function getDefaultOwnerId() {
791 return \Drupal::currentUser()->id();