annotate core/modules/content_translation/src/ContentTranslationHandler.php @ 16:c2387f117808

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