annotate core/modules/content_translation/src/ContentTranslationHandler.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\content_translation;
Chris@0 4
Chris@0 5 use Drupal\Core\Access\AccessResult;
Chris@18 6 use Drupal\Core\Datetime\DateFormatterInterface;
Chris@0 7 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
Chris@0 8 use Drupal\Core\Entity\EntityChangedInterface;
Chris@14 9 use Drupal\Core\Entity\EntityChangesDetectionTrait;
Chris@0 10 use Drupal\Core\Entity\EntityHandlerInterface;
Chris@0 11 use Drupal\Core\Entity\EntityInterface;
Chris@18 12 use Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface;
Chris@0 13 use Drupal\Core\Entity\EntityTypeInterface;
Chris@18 14 use Drupal\Core\Entity\EntityTypeManagerInterface;
Chris@0 15 use Drupal\Core\Field\BaseFieldDefinition;
Chris@0 16 use Drupal\Core\Form\FormStateInterface;
Chris@0 17 use Drupal\Core\Language\LanguageInterface;
Chris@0 18 use Drupal\Core\Language\LanguageManagerInterface;
Chris@14 19 use Drupal\Core\Messenger\MessengerInterface;
Chris@0 20 use Drupal\Core\Render\Element;
Chris@0 21 use Drupal\Core\Session\AccountInterface;
Chris@14 22 use Drupal\Core\StringTranslation\StringTranslationTrait;
Chris@0 23 use Drupal\user\Entity\User;
Chris@0 24 use Drupal\user\EntityOwnerInterface;
Chris@0 25 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@0 26
Chris@0 27 /**
Chris@0 28 * Base class for content translation handlers.
Chris@0 29 *
Chris@0 30 * @ingroup entity_api
Chris@0 31 */
Chris@0 32 class ContentTranslationHandler implements ContentTranslationHandlerInterface, EntityHandlerInterface {
Chris@14 33
Chris@14 34 use EntityChangesDetectionTrait;
Chris@0 35 use DependencySerializationTrait;
Chris@14 36 use StringTranslationTrait;
Chris@0 37
Chris@0 38 /**
Chris@0 39 * The type of the entity being translated.
Chris@0 40 *
Chris@0 41 * @var string
Chris@0 42 */
Chris@0 43 protected $entityTypeId;
Chris@0 44
Chris@0 45 /**
Chris@0 46 * Information about the entity type.
Chris@0 47 *
Chris@0 48 * @var \Drupal\Core\Entity\EntityTypeInterface
Chris@0 49 */
Chris@0 50 protected $entityType;
Chris@0 51
Chris@0 52 /**
Chris@0 53 * The language manager.
Chris@0 54 *
Chris@0 55 * @var \Drupal\Core\Language\LanguageManagerInterface
Chris@0 56 */
Chris@0 57 protected $languageManager;
Chris@0 58
Chris@0 59 /**
Chris@0 60 * The content translation manager.
Chris@0 61 *
Chris@0 62 * @var \Drupal\content_translation\ContentTranslationManagerInterface
Chris@0 63 */
Chris@0 64 protected $manager;
Chris@0 65
Chris@0 66 /**
Chris@14 67 * The entity type manager.
Chris@14 68 *
Chris@14 69 * @var \Drupal\Core\Entity\EntityTypeManagerInterface
Chris@14 70 */
Chris@14 71 protected $entityTypeManager;
Chris@14 72
Chris@14 73 /**
Chris@0 74 * The current user.
Chris@0 75 *
Chris@0 76 * @var \Drupal\Core\Session\AccountInterface
Chris@0 77 */
Chris@0 78 protected $currentUser;
Chris@0 79
Chris@0 80 /**
Chris@0 81 * The array of installed field storage definitions for the entity type, keyed
Chris@0 82 * by field name.
Chris@0 83 *
Chris@0 84 * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
Chris@0 85 */
Chris@0 86 protected $fieldStorageDefinitions;
Chris@0 87
Chris@0 88 /**
Chris@14 89 * The messenger service.
Chris@14 90 *
Chris@14 91 * @var \Drupal\Core\Messenger\MessengerInterface
Chris@14 92 */
Chris@14 93 protected $messenger;
Chris@14 94
Chris@14 95 /**
Chris@18 96 * The date formatter service.
Chris@18 97 *
Chris@18 98 * @var \Drupal\Core\Datetime\DateFormatterInterface
Chris@18 99 */
Chris@18 100 protected $dateFormatter;
Chris@18 101
Chris@18 102 /**
Chris@0 103 * Initializes an instance of the content translation controller.
Chris@0 104 *
Chris@0 105 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
Chris@0 106 * The info array of the given entity type.
Chris@0 107 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
Chris@0 108 * The language manager.
Chris@0 109 * @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
Chris@0 110 * The content translation manager service.
Chris@18 111 * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
Chris@18 112 * The entity type manager.
Chris@0 113 * @param \Drupal\Core\Session\AccountInterface $current_user
Chris@0 114 * The current user.
Chris@14 115 * @param \Drupal\Core\Messenger\MessengerInterface $messenger
Chris@14 116 * The messenger service.
Chris@18 117 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
Chris@18 118 * The date formatter service.
Chris@0 119 */
Chris@18 120 public function __construct(EntityTypeInterface $entity_type, LanguageManagerInterface $language_manager, ContentTranslationManagerInterface $manager, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user, MessengerInterface $messenger, DateFormatterInterface $date_formatter, EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository = NULL) {
Chris@0 121 $this->entityTypeId = $entity_type->id();
Chris@0 122 $this->entityType = $entity_type;
Chris@0 123 $this->languageManager = $language_manager;
Chris@0 124 $this->manager = $manager;
Chris@18 125 $this->entityTypeManager = $entity_type_manager;
Chris@0 126 $this->currentUser = $current_user;
Chris@18 127 if (!$entity_last_installed_schema_repository) {
Chris@18 128 @trigger_error('Calling ContentTranslationHandler::__construct() with the $entity_last_installed_schema_repository argument is supported in drupal:8.7.0 and will be required before drupal:9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
Chris@18 129 $entity_last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');
Chris@18 130 }
Chris@18 131 $this->fieldStorageDefinitions = $entity_last_installed_schema_repository->getLastInstalledFieldStorageDefinitions($this->entityTypeId);
Chris@14 132 $this->messenger = $messenger;
Chris@18 133 $this->dateFormatter = $date_formatter;
Chris@0 134 }
Chris@0 135
Chris@0 136 /**
Chris@0 137 * {@inheritdoc}
Chris@0 138 */
Chris@0 139 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
Chris@0 140 return new static(
Chris@0 141 $entity_type,
Chris@0 142 $container->get('language_manager'),
Chris@0 143 $container->get('content_translation.manager'),
Chris@18 144 $container->get('entity_type.manager'),
Chris@14 145 $container->get('current_user'),
Chris@18 146 $container->get('messenger'),
Chris@18 147 $container->get('date.formatter'),
Chris@18 148 $container->get('entity.last_installed_schema.repository')
Chris@0 149 );
Chris@0 150 }
Chris@0 151
Chris@0 152 /**
Chris@0 153 * {@inheritdoc}
Chris@0 154 */
Chris@0 155 public function getFieldDefinitions() {
Chris@0 156 $definitions = [];
Chris@0 157
Chris@0 158 $definitions['content_translation_source'] = BaseFieldDefinition::create('language')
Chris@0 159 ->setLabel(t('Translation source'))
Chris@0 160 ->setDescription(t('The source language from which this translation was created.'))
Chris@0 161 ->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
Chris@0 162 ->setInitialValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
Chris@0 163 ->setRevisionable(TRUE)
Chris@0 164 ->setTranslatable(TRUE);
Chris@0 165
Chris@0 166 $definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
Chris@0 167 ->setLabel(t('Translation outdated'))
Chris@0 168 ->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
Chris@0 169 ->setDefaultValue(FALSE)
Chris@0 170 ->setInitialValue(FALSE)
Chris@0 171 ->setRevisionable(TRUE)
Chris@0 172 ->setTranslatable(TRUE);
Chris@0 173
Chris@0 174 if (!$this->hasAuthor()) {
Chris@0 175 $definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
Chris@0 176 ->setLabel(t('Translation author'))
Chris@0 177 ->setDescription(t('The author of this translation.'))
Chris@0 178 ->setSetting('target_type', 'user')
Chris@0 179 ->setSetting('handler', 'default')
Chris@0 180 ->setRevisionable(TRUE)
Chris@0 181 ->setDefaultValueCallback(get_class($this) . '::getDefaultOwnerId')
Chris@0 182 ->setTranslatable(TRUE);
Chris@0 183 }
Chris@0 184
Chris@0 185 if (!$this->hasPublishedStatus()) {
Chris@0 186 $definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
Chris@0 187 ->setLabel(t('Translation status'))
Chris@0 188 ->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
Chris@0 189 ->setDefaultValue(TRUE)
Chris@0 190 ->setInitialValue(TRUE)
Chris@0 191 ->setRevisionable(TRUE)
Chris@0 192 ->setTranslatable(TRUE);
Chris@0 193 }
Chris@0 194
Chris@0 195 if (!$this->hasCreatedTime()) {
Chris@0 196 $definitions['content_translation_created'] = BaseFieldDefinition::create('created')
Chris@0 197 ->setLabel(t('Translation created time'))
Chris@0 198 ->setDescription(t('The Unix timestamp when the translation was created.'))
Chris@0 199 ->setRevisionable(TRUE)
Chris@0 200 ->setTranslatable(TRUE);
Chris@0 201 }
Chris@0 202
Chris@0 203 if (!$this->hasChangedTime()) {
Chris@0 204 $definitions['content_translation_changed'] = BaseFieldDefinition::create('changed')
Chris@0 205 ->setLabel(t('Translation changed time'))
Chris@0 206 ->setDescription(t('The Unix timestamp when the translation was most recently saved.'))
Chris@0 207 ->setRevisionable(TRUE)
Chris@0 208 ->setTranslatable(TRUE);
Chris@0 209 }
Chris@0 210
Chris@0 211 return $definitions;
Chris@0 212 }
Chris@0 213
Chris@0 214 /**
Chris@0 215 * Checks whether the entity type supports author natively.
Chris@0 216 *
Chris@0 217 * @return bool
Chris@0 218 * TRUE if metadata is natively supported, FALSE otherwise.
Chris@0 219 */
Chris@0 220 protected function hasAuthor() {
Chris@0 221 // Check for field named uid, but only in case the entity implements the
Chris@0 222 // EntityOwnerInterface. This helps to exclude cases, where the uid is
Chris@0 223 // defined as field name, but is not meant to be an owner field; for
Chris@0 224 // instance, the User entity.
Chris@0 225 return $this->entityType->entityClassImplements(EntityOwnerInterface::class) && $this->checkFieldStorageDefinitionTranslatability('uid');
Chris@0 226 }
Chris@0 227
Chris@0 228 /**
Chris@0 229 * Checks whether the entity type supports published status natively.
Chris@0 230 *
Chris@0 231 * @return bool
Chris@0 232 * TRUE if metadata is natively supported, FALSE otherwise.
Chris@0 233 */
Chris@0 234 protected function hasPublishedStatus() {
Chris@0 235 return $this->checkFieldStorageDefinitionTranslatability('status');
Chris@0 236 }
Chris@0 237
Chris@0 238 /**
Chris@0 239 * Checks whether the entity type supports modification time natively.
Chris@0 240 *
Chris@0 241 * @return bool
Chris@0 242 * TRUE if metadata is natively supported, FALSE otherwise.
Chris@0 243 */
Chris@0 244 protected function hasChangedTime() {
Chris@0 245 return $this->entityType->entityClassImplements(EntityChangedInterface::class) && $this->checkFieldStorageDefinitionTranslatability('changed');
Chris@0 246 }
Chris@0 247
Chris@0 248 /**
Chris@0 249 * Checks whether the entity type supports creation time natively.
Chris@0 250 *
Chris@0 251 * @return bool
Chris@0 252 * TRUE if metadata is natively supported, FALSE otherwise.
Chris@0 253 */
Chris@0 254 protected function hasCreatedTime() {
Chris@0 255 return $this->checkFieldStorageDefinitionTranslatability('created');
Chris@0 256 }
Chris@0 257
Chris@0 258 /**
Chris@0 259 * Checks the field storage definition for translatability support.
Chris@0 260 *
Chris@0 261 * Checks whether the given field is defined in the field storage definitions
Chris@0 262 * and if its definition specifies it as translatable.
Chris@0 263 *
Chris@0 264 * @param string $field_name
Chris@0 265 * The name of the field.
Chris@0 266 *
Chris@0 267 * @return bool
Chris@0 268 * TRUE if translatable field storage definition exists, FALSE otherwise.
Chris@0 269 */
Chris@0 270 protected function checkFieldStorageDefinitionTranslatability($field_name) {
Chris@0 271 return array_key_exists($field_name, $this->fieldStorageDefinitions) && $this->fieldStorageDefinitions[$field_name]->isTranslatable();
Chris@0 272 }
Chris@0 273
Chris@0 274 /**
Chris@0 275 * {@inheritdoc}
Chris@0 276 */
Chris@0 277 public function retranslate(EntityInterface $entity, $langcode = NULL) {
Chris@0 278 $updated_langcode = !empty($langcode) ? $langcode : $entity->language()->getId();
Chris@0 279 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
Chris@0 280 $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
Chris@0 281 ->setOutdated($langcode != $updated_langcode);
Chris@0 282 }
Chris@0 283 }
Chris@0 284
Chris@0 285 /**
Chris@0 286 * {@inheritdoc}
Chris@0 287 */
Chris@0 288 public function getTranslationAccess(EntityInterface $entity, $op) {
Chris@0 289 // @todo Move this logic into a translation access control handler checking also
Chris@0 290 // the translation language and the given account.
Chris@0 291 $entity_type = $entity->getEntityType();
Chris@0 292 $translate_permission = TRUE;
Chris@0 293 // If no permission granularity is defined this entity type does not need an
Chris@0 294 // explicit translate permission.
Chris@0 295 if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
Chris@0 296 $translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
Chris@0 297 }
Chris@0 298 return AccessResult::allowedIf($translate_permission && $this->currentUser->hasPermission("$op content translations"))->cachePerPermissions();
Chris@0 299 }
Chris@0 300
Chris@0 301 /**
Chris@0 302 * {@inheritdoc}
Chris@0 303 */
Chris@0 304 public function getSourceLangcode(FormStateInterface $form_state) {
Chris@0 305 if ($source = $form_state->get(['content_translation', 'source'])) {
Chris@0 306 return $source->getId();
Chris@0 307 }
Chris@0 308 return FALSE;
Chris@0 309 }
Chris@0 310
Chris@0 311 /**
Chris@0 312 * {@inheritdoc}
Chris@0 313 */
Chris@0 314 public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
Chris@14 315 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
Chris@14 316
Chris@0 317 $form_object = $form_state->getFormObject();
Chris@0 318 $form_langcode = $form_object->getFormLangcode($form_state);
Chris@0 319 $entity_langcode = $entity->getUntranslated()->language()->getId();
Chris@0 320 $source_langcode = $this->getSourceLangcode($form_state);
Chris@0 321
Chris@0 322 $new_translation = !empty($source_langcode);
Chris@0 323 $translations = $entity->getTranslationLanguages();
Chris@0 324 if ($new_translation) {
Chris@0 325 // Make sure a new translation does not appear as existing yet.
Chris@0 326 unset($translations[$form_langcode]);
Chris@0 327 }
Chris@0 328 $is_translation = !$form_object->isDefaultFormLangcode($form_state);
Chris@0 329 $has_translations = count($translations) > 1;
Chris@0 330
Chris@0 331 // Adjust page title to specify the current language being edited, if we
Chris@0 332 // have at least one translation.
Chris@0 333 $languages = $this->languageManager->getLanguages();
Chris@0 334 if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
Chris@0 335 $title = $this->entityFormTitle($entity);
Chris@0 336 // When editing the original values display just the entity label.
Chris@0 337 if ($is_translation) {
Chris@0 338 $t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title];
Chris@0 339 $title = empty($source_langcode) ? t('@title [%language translation]', $t_args) : t('Create %language translation of %title', $t_args);
Chris@0 340 }
Chris@0 341 $form['#title'] = $title;
Chris@0 342 }
Chris@0 343
Chris@0 344 // Display source language selector only if we are creating a new
Chris@0 345 // translation and there are at least two translations available.
Chris@0 346 if ($has_translations && $new_translation) {
Chris@0 347 $form['source_langcode'] = [
Chris@0 348 '#type' => 'details',
Chris@0 349 '#title' => t('Source language: @language', ['@language' => $languages[$source_langcode]->getName()]),
Chris@0 350 '#tree' => TRUE,
Chris@0 351 '#weight' => -100,
Chris@0 352 '#multilingual' => TRUE,
Chris@0 353 'source' => [
Chris@0 354 '#title' => t('Select source language'),
Chris@0 355 '#title_display' => 'invisible',
Chris@0 356 '#type' => 'select',
Chris@0 357 '#default_value' => $source_langcode,
Chris@0 358 '#options' => [],
Chris@0 359 ],
Chris@0 360 'submit' => [
Chris@0 361 '#type' => 'submit',
Chris@0 362 '#value' => t('Change'),
Chris@0 363 '#submit' => [[$this, 'entityFormSourceChange']],
Chris@0 364 ],
Chris@0 365 ];
Chris@0 366 foreach ($this->languageManager->getLanguages() as $language) {
Chris@0 367 if (isset($translations[$language->getId()])) {
Chris@0 368 $form['source_langcode']['source']['#options'][$language->getId()] = $language->getName();
Chris@0 369 }
Chris@0 370 }
Chris@0 371 }
Chris@0 372
Chris@0 373 // Locate the language widget.
Chris@0 374 $langcode_key = $this->entityType->getKey('langcode');
Chris@0 375 if (isset($form[$langcode_key])) {
Chris@0 376 $language_widget = &$form[$langcode_key];
Chris@0 377 }
Chris@0 378
Chris@0 379 // If we are editing the source entity, limit the list of languages so that
Chris@0 380 // it is not possible to switch to a language for which a translation
Chris@0 381 // already exists. Note that this will only work if the widget is structured
Chris@0 382 // like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
Chris@0 383 if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
Chris@0 384 $language_select = &$language_widget['widget'][0]['value'];
Chris@0 385 if ($language_select['#type'] == 'language_select') {
Chris@0 386 $options = [];
Chris@0 387 foreach ($this->languageManager->getLanguages() as $language) {
Chris@0 388 // Show the current language, and the languages for which no
Chris@0 389 // translation already exists.
Chris@0 390 if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
Chris@0 391 $options[$language->getId()] = $language->getName();
Chris@0 392 }
Chris@0 393 }
Chris@0 394 $language_select['#options'] = $options;
Chris@0 395 }
Chris@0 396 }
Chris@0 397 if ($is_translation) {
Chris@0 398 if (isset($language_widget)) {
Chris@0 399 $language_widget['widget']['#access'] = FALSE;
Chris@0 400 }
Chris@0 401
Chris@0 402 // Replace the delete button with the delete translation one.
Chris@0 403 if (!$new_translation) {
Chris@0 404 $weight = 100;
Chris@0 405 foreach (['delete', 'submit'] as $key) {
Chris@0 406 if (isset($form['actions'][$key]['weight'])) {
Chris@0 407 $weight = $form['actions'][$key]['weight'];
Chris@0 408 break;
Chris@0 409 }
Chris@0 410 }
Chris@14 411 /** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
Chris@14 412 $delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
Chris@14 413 $access = $delete_access->isAllowed() && (
Chris@14 414 $this->getTranslationAccess($entity, 'delete')->isAllowed() ||
Chris@14 415 ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form'))
Chris@14 416 );
Chris@0 417 $form['actions']['delete_translation'] = [
Chris@0 418 '#type' => 'submit',
Chris@0 419 '#value' => t('Delete translation'),
Chris@0 420 '#weight' => $weight,
Chris@0 421 '#submit' => [[$this, 'entityFormDeleteTranslation']],
Chris@0 422 '#access' => $access,
Chris@0 423 ];
Chris@0 424 }
Chris@0 425
Chris@0 426 // Always remove the delete button on translation forms.
Chris@0 427 unset($form['actions']['delete']);
Chris@0 428 }
Chris@0 429
Chris@0 430 // We need to display the translation tab only when there is at least one
Chris@0 431 // translation available or a new one is about to be created.
Chris@0 432 if ($new_translation || $has_translations) {
Chris@0 433 $form['content_translation'] = [
Chris@0 434 '#type' => 'details',
Chris@0 435 '#title' => t('Translation'),
Chris@0 436 '#tree' => TRUE,
Chris@0 437 '#weight' => 10,
Chris@0 438 '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update')->isAllowed(),
Chris@0 439 '#multilingual' => TRUE,
Chris@0 440 ];
Chris@0 441
Chris@0 442 if (isset($form['advanced'])) {
Chris@0 443 $form['content_translation'] += [
Chris@0 444 '#group' => 'advanced',
Chris@0 445 '#weight' => 100,
Chris@0 446 '#attributes' => [
Chris@0 447 'class' => ['entity-translation-options'],
Chris@0 448 ],
Chris@0 449 ];
Chris@0 450 }
Chris@0 451
Chris@0 452 // A new translation is enabled by default.
Chris@0 453 $metadata = $this->manager->getTranslationMetadata($entity);
Chris@0 454 $status = $new_translation || $metadata->isPublished();
Chris@0 455 // If there is only one published translation we cannot unpublish it,
Chris@0 456 // since there would be nothing left to display.
Chris@0 457 $enabled = TRUE;
Chris@0 458 if ($status) {
Chris@0 459 $published = 0;
Chris@0 460 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
Chris@0 461 $published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
Chris@0 462 ->isPublished();
Chris@0 463 }
Chris@0 464 $enabled = $published > 1;
Chris@0 465 }
Chris@0 466 $description = $enabled ?
Chris@0 467 t('An unpublished translation will not be visible without translation permissions.') :
Chris@0 468 t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
Chris@0 469
Chris@0 470 $form['content_translation']['status'] = [
Chris@0 471 '#type' => 'checkbox',
Chris@0 472 '#title' => t('This translation is published'),
Chris@0 473 '#default_value' => $status,
Chris@0 474 '#description' => $description,
Chris@0 475 '#disabled' => !$enabled,
Chris@0 476 ];
Chris@0 477
Chris@0 478 $translate = !$new_translation && $metadata->isOutdated();
Chris@14 479 $outdated_access = !ContentTranslationManager::isPendingRevisionSupportEnabled($entity->getEntityTypeId(), $entity->bundle());
Chris@14 480 if (!$outdated_access) {
Chris@14 481 $form['content_translation']['outdated'] = [
Chris@14 482 '#markup' => $this->t('Translations cannot be flagged as outdated when content is moderated.'),
Chris@14 483 ];
Chris@14 484 }
Chris@14 485 elseif (!$translate) {
Chris@0 486 $form['content_translation']['retranslate'] = [
Chris@0 487 '#type' => 'checkbox',
Chris@0 488 '#title' => t('Flag other translations as outdated'),
Chris@0 489 '#default_value' => FALSE,
Chris@0 490 '#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.'),
Chris@14 491 '#access' => $outdated_access,
Chris@0 492 ];
Chris@0 493 }
Chris@0 494 else {
Chris@0 495 $form['content_translation']['outdated'] = [
Chris@0 496 '#type' => 'checkbox',
Chris@0 497 '#title' => t('This translation needs to be updated'),
Chris@0 498 '#default_value' => $translate,
Chris@0 499 '#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'),
Chris@14 500 '#access' => $outdated_access,
Chris@0 501 ];
Chris@0 502 $form['content_translation']['#open'] = TRUE;
Chris@0 503 }
Chris@0 504
Chris@0 505 // Default to the anonymous user.
Chris@0 506 $uid = 0;
Chris@0 507 if ($new_translation) {
Chris@0 508 $uid = $this->currentUser->id();
Chris@0 509 }
Chris@0 510 elseif (($account = $metadata->getAuthor()) && $account->id()) {
Chris@0 511 $uid = $account->id();
Chris@0 512 }
Chris@0 513 $form['content_translation']['uid'] = [
Chris@0 514 '#type' => 'entity_autocomplete',
Chris@0 515 '#title' => t('Authored by'),
Chris@0 516 '#target_type' => 'user',
Chris@0 517 '#default_value' => User::load($uid),
Chris@0 518 // Validation is done by static::entityFormValidate().
Chris@0 519 '#validate_reference' => FALSE,
Chris@0 520 '#maxlength' => 60,
Chris@0 521 '#description' => t('Leave blank for %anonymous.', ['%anonymous' => \Drupal::config('user.settings')->get('anonymous')]),
Chris@0 522 ];
Chris@0 523
Chris@0 524 $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime();
Chris@0 525 $form['content_translation']['created'] = [
Chris@0 526 '#type' => 'textfield',
Chris@0 527 '#title' => t('Authored on'),
Chris@0 528 '#maxlength' => 25,
Chris@18 529 '#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.', [
Chris@18 530 '%time' => $this->dateFormatter->format(REQUEST_TIME, 'custom', 'Y-m-d H:i:s O'),
Chris@18 531 '%timezone' => $this->dateFormatter->format(REQUEST_TIME, 'custom', 'O'),
Chris@18 532 ]),
Chris@18 533 '#default_value' => $new_translation || !$date ? '' : $this->dateFormatter->format($date, 'custom', 'Y-m-d H:i:s O'),
Chris@0 534 ];
Chris@0 535
Chris@0 536 $form['#process'][] = [$this, 'entityFormSharedElements'];
Chris@0 537 }
Chris@0 538
Chris@0 539 // Process the submitted values before they are stored.
Chris@0 540 $form['#entity_builders'][] = [$this, 'entityFormEntityBuild'];
Chris@0 541
Chris@0 542 // Handle entity validation.
Chris@0 543 $form['#validate'][] = [$this, 'entityFormValidate'];
Chris@0 544
Chris@0 545 // Handle entity deletion.
Chris@0 546 if (isset($form['actions']['delete'])) {
Chris@0 547 $form['actions']['delete']['#submit'][] = [$this, 'entityFormDelete'];
Chris@0 548 }
Chris@0 549
Chris@0 550 // Handle entity form submission before the entity has been saved.
Chris@0 551 foreach (Element::children($form['actions']) as $action) {
Chris@0 552 if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
Chris@0 553 array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
Chris@0 554 }
Chris@0 555 }
Chris@0 556 }
Chris@0 557
Chris@0 558 /**
Chris@0 559 * Process callback: determines which elements get clue in the form.
Chris@0 560 *
Chris@0 561 * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
Chris@0 562 */
Chris@0 563 public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
Chris@0 564 static $ignored_types;
Chris@0 565
Chris@0 566 // @todo Find a more reliable way to determine if a form element concerns a
Chris@0 567 // multilingual value.
Chris@0 568 if (!isset($ignored_types)) {
Chris@0 569 $ignored_types = array_flip(['actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details']);
Chris@0 570 }
Chris@0 571
Chris@14 572 /** @var \Drupal\Core\Entity\ContentEntityForm $form_object */
Chris@14 573 $form_object = $form_state->getFormObject();
Chris@14 574 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
Chris@14 575 $entity = $form_object->getEntity();
Chris@14 576 $display_translatability_clue = !$entity->isDefaultTranslationAffectedOnly();
Chris@14 577 $hide_untranslatable_fields = $entity->isDefaultTranslationAffectedOnly() && !$entity->isDefaultTranslation();
Chris@14 578 $translation_form = $form_state->get(['content_translation', 'translation_form']);
Chris@14 579 $display_warning = FALSE;
Chris@14 580
Chris@14 581 // We use field definitions to identify untranslatable field widgets to be
Chris@14 582 // hidden. Fields that are not involved in translation changes checks should
Chris@14 583 // not be affected by this logic (the "revision_log" field, for instance).
Chris@14 584 $field_definitions = array_diff_key($entity->getFieldDefinitions(), array_flip($this->getFieldsToSkipFromTranslationChangesCheck($entity)));
Chris@14 585
Chris@0 586 foreach (Element::children($element) as $key) {
Chris@0 587 if (!isset($element[$key]['#type'])) {
Chris@0 588 $this->entityFormSharedElements($element[$key], $form_state, $form);
Chris@0 589 }
Chris@0 590 else {
Chris@0 591 // Ignore non-widget form elements.
Chris@0 592 if (isset($ignored_types[$element[$key]['#type']])) {
Chris@0 593 continue;
Chris@0 594 }
Chris@0 595 // Elements are considered to be non multilingual by default.
Chris@0 596 if (empty($element[$key]['#multilingual'])) {
Chris@0 597 // If we are displaying a multilingual entity form we need to provide
Chris@14 598 // translatability clues, otherwise the non-multilingual form elements
Chris@14 599 // should be hidden.
Chris@14 600 if (!$translation_form) {
Chris@14 601 if ($display_translatability_clue) {
Chris@14 602 $this->addTranslatabilityClue($element[$key]);
Chris@14 603 }
Chris@14 604 // Hide widgets for untranslatable fields.
Chris@14 605 if ($hide_untranslatable_fields && isset($field_definitions[$key])) {
Chris@14 606 $element[$key]['#access'] = FALSE;
Chris@14 607 $display_warning = TRUE;
Chris@14 608 }
Chris@0 609 }
Chris@0 610 else {
Chris@0 611 $element[$key]['#access'] = FALSE;
Chris@0 612 }
Chris@0 613 }
Chris@0 614 }
Chris@0 615 }
Chris@0 616
Chris@14 617 if ($display_warning && !$form_state->isSubmitted() && !$form_state->isRebuilding()) {
Chris@14 618 $url = $entity->getUntranslated()->toUrl('edit-form')->toString();
Chris@14 619 $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]));
Chris@14 620 }
Chris@14 621
Chris@0 622 return $element;
Chris@0 623 }
Chris@0 624
Chris@0 625 /**
Chris@0 626 * Adds a clue about the form element translatability.
Chris@0 627 *
Chris@0 628 * If the given element does not have a #title attribute, the function is
Chris@0 629 * recursively applied to child elements.
Chris@0 630 *
Chris@0 631 * @param array $element
Chris@0 632 * A form element array.
Chris@0 633 */
Chris@0 634 protected function addTranslatabilityClue(&$element) {
Chris@0 635 static $suffix, $fapi_title_elements;
Chris@0 636
Chris@0 637 // Elements which can have a #title attribute according to FAPI Reference.
Chris@0 638 if (!isset($suffix)) {
Chris@0 639 $suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
Chris@0 640 $fapi_title_elements = array_flip(['checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight']);
Chris@0 641 }
Chris@0 642
Chris@0 643 // Update #title attribute for all elements that are allowed to have a
Chris@0 644 // #title attribute according to the Form API Reference. The reason for this
Chris@0 645 // check is because some elements have a #title attribute even though it is
Chris@0 646 // not rendered; for instance, field containers.
Chris@0 647 if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
Chris@0 648 $element['#title'] .= $suffix;
Chris@0 649 }
Chris@0 650 // If the current element does not have a (valid) title, try child elements.
Chris@0 651 elseif ($children = Element::children($element)) {
Chris@0 652 foreach ($children as $delta) {
Chris@0 653 $this->addTranslatabilityClue($element[$delta], $suffix);
Chris@0 654 }
Chris@0 655 }
Chris@0 656 // If there are no children, fall back to the current #title attribute if it
Chris@0 657 // exists.
Chris@0 658 elseif (isset($element['#title'])) {
Chris@0 659 $element['#title'] .= $suffix;
Chris@0 660 }
Chris@0 661 }
Chris@0 662
Chris@0 663 /**
Chris@0 664 * Entity builder method.
Chris@0 665 *
Chris@0 666 * @param string $entity_type
Chris@0 667 * The type of the entity.
Chris@0 668 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@0 669 * The entity whose form is being built.
Chris@0 670 *
Chris@0 671 * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
Chris@0 672 */
Chris@0 673 public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
Chris@0 674 $form_object = $form_state->getFormObject();
Chris@0 675 $form_langcode = $form_object->getFormLangcode($form_state);
Chris@0 676 $values = &$form_state->getValue('content_translation', []);
Chris@0 677
Chris@0 678 $metadata = $this->manager->getTranslationMetadata($entity);
Chris@0 679 $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
Chris@0 680 $metadata->setPublished(!empty($values['status']));
Chris@0 681 $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME);
Chris@0 682
Chris@0 683 $source_langcode = $this->getSourceLangcode($form_state);
Chris@0 684 if ($source_langcode) {
Chris@0 685 $metadata->setSource($source_langcode);
Chris@0 686 }
Chris@0 687
Chris@0 688 $metadata->setOutdated(!empty($values['outdated']));
Chris@0 689 if (!empty($values['retranslate'])) {
Chris@0 690 $this->retranslate($entity, $form_langcode);
Chris@0 691 }
Chris@0 692 }
Chris@0 693
Chris@0 694 /**
Chris@0 695 * Form validation handler for ContentTranslationHandler::entityFormAlter().
Chris@0 696 *
Chris@0 697 * Validates the submitted content translation metadata.
Chris@0 698 */
Chris@0 699 public function entityFormValidate($form, FormStateInterface $form_state) {
Chris@0 700 if (!$form_state->isValueEmpty('content_translation')) {
Chris@0 701 $translation = $form_state->getValue('content_translation');
Chris@0 702 // Validate the "authored by" field.
Chris@0 703 if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
Chris@18 704 $form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', ['%name' => $account->getAccountName()]));
Chris@0 705 }
Chris@0 706 // Validate the "authored on" field.
Chris@0 707 if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
Chris@0 708 $form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
Chris@0 709 }
Chris@0 710 }
Chris@0 711 }
Chris@0 712
Chris@0 713 /**
Chris@0 714 * Form submission handler for ContentTranslationHandler::entityFormAlter().
Chris@0 715 *
Chris@0 716 * Updates metadata fields, which should be updated only after the validation
Chris@0 717 * has run and before the entity is saved.
Chris@0 718 */
Chris@0 719 public function entityFormSubmit($form, FormStateInterface $form_state) {
Chris@0 720 /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
Chris@0 721 $form_object = $form_state->getFormObject();
Chris@0 722 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
Chris@0 723 $entity = $form_object->getEntity();
Chris@0 724
Chris@0 725 // ContentEntityForm::submit will update the changed timestamp on submit
Chris@0 726 // after the entity has been validated, so that it does not break the
Chris@0 727 // EntityChanged constraint validator. The content translation metadata
Chris@0 728 // field for the changed timestamp does not have such a constraint defined
Chris@14 729 // at the moment, but it is correct to update its value in a submission
Chris@0 730 // handler as well and have the same logic like in the Form API.
Chris@0 731 if ($entity->hasField('content_translation_changed')) {
Chris@0 732 $metadata = $this->manager->getTranslationMetadata($entity);
Chris@0 733 $metadata->setChangedTime(REQUEST_TIME);
Chris@0 734 }
Chris@0 735 }
Chris@0 736
Chris@0 737 /**
Chris@0 738 * Form submission handler for ContentTranslationHandler::entityFormAlter().
Chris@0 739 *
Chris@0 740 * Takes care of the source language change.
Chris@0 741 */
Chris@0 742 public function entityFormSourceChange($form, FormStateInterface $form_state) {
Chris@0 743 $form_object = $form_state->getFormObject();
Chris@0 744 $entity = $form_object->getEntity();
Chris@0 745 $source = $form_state->getValue(['source_langcode', 'source']);
Chris@0 746
Chris@0 747 $entity_type_id = $entity->getEntityTypeId();
Chris@0 748 $form_state->setRedirect("entity.$entity_type_id.content_translation_add", [
Chris@0 749 $entity_type_id => $entity->id(),
Chris@0 750 'source' => $source,
Chris@0 751 'target' => $form_object->getFormLangcode($form_state),
Chris@0 752 ]);
Chris@0 753 $languages = $this->languageManager->getLanguages();
Chris@17 754 $this->messenger->addStatus(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
Chris@0 755 }
Chris@0 756
Chris@0 757 /**
Chris@0 758 * Form submission handler for ContentTranslationHandler::entityFormAlter().
Chris@0 759 *
Chris@0 760 * Takes care of entity deletion.
Chris@0 761 */
Chris@0 762 public function entityFormDelete($form, FormStateInterface $form_state) {
Chris@16 763 $form_object = $form_state->getFormObject();
Chris@0 764 $entity = $form_object->getEntity();
Chris@0 765 if (count($entity->getTranslationLanguages()) > 1) {
Chris@17 766 $this->messenger->addWarning(t('This will delete all the translations of %label.', ['%label' => $entity->label()]));
Chris@0 767 }
Chris@0 768 }
Chris@0 769
Chris@0 770 /**
Chris@0 771 * Form submission handler for ContentTranslationHandler::entityFormAlter().
Chris@0 772 *
Chris@0 773 * Takes care of content translation deletion.
Chris@0 774 */
Chris@0 775 public function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
Chris@0 776 /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
Chris@0 777 $form_object = $form_state->getFormObject();
Chris@0 778 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
Chris@0 779 $entity = $form_object->getEntity();
Chris@0 780 $entity_type_id = $entity->getEntityTypeId();
Chris@0 781 if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
Chris@18 782 $form_state->setRedirectUrl($entity->toUrl('delete-form'));
Chris@0 783 }
Chris@0 784 else {
Chris@0 785 $form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
Chris@0 786 $entity_type_id => $entity->id(),
Chris@0 787 'language' => $form_object->getFormLangcode($form_state),
Chris@0 788 ]);
Chris@0 789 }
Chris@0 790 }
Chris@0 791
Chris@0 792 /**
Chris@0 793 * Returns the title to be used for the entity form page.
Chris@0 794 *
Chris@0 795 * @param \Drupal\Core\Entity\EntityInterface $entity
Chris@0 796 * The entity whose form is being altered.
Chris@0 797 *
Chris@0 798 * @return string|null
Chris@0 799 * The label of the entity, or NULL if there is no label defined.
Chris@0 800 */
Chris@0 801 protected function entityFormTitle(EntityInterface $entity) {
Chris@0 802 return $entity->label();
Chris@0 803 }
Chris@0 804
Chris@0 805 /**
Chris@0 806 * Default value callback for the owner base field definition.
Chris@0 807 *
Chris@0 808 * @return int
Chris@0 809 * The user ID.
Chris@0 810 */
Chris@0 811 public static function getDefaultOwnerId() {
Chris@0 812 return \Drupal::currentUser()->id();
Chris@0 813 }
Chris@0 814
Chris@0 815 }