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