annotate core/modules/content_translation/src/ContentTranslationHandler.php @ 0:4c8ae668cc8c

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