5 * Allows entities to be translated into different languages.
8 use Drupal\content_translation\BundleTranslationSettingsInterface;
9 use Drupal\content_translation\ContentTranslationManager;
10 use Drupal\Core\Access\AccessResult;
11 use Drupal\Core\Entity\ContentEntityFormInterface;
12 use Drupal\Core\Entity\ContentEntityInterface;
13 use Drupal\Core\Entity\EntityInterface;
14 use Drupal\Core\Entity\EntityTypeInterface;
15 use Drupal\Core\Form\FormStateInterface;
16 use Drupal\Core\Language\LanguageInterface;
17 use Drupal\Core\Routing\RouteMatchInterface;
18 use Drupal\Core\StringTranslation\TranslatableMarkup;
21 * Implements hook_help().
23 function content_translation_help($route_name, RouteMatchInterface $route_match) {
24 switch ($route_name) {
25 case 'help.page.content_translation':
27 $output .= '<h3>' . t('About') . '</h3>';
28 $output .= '<p>' . t('The Content Translation module allows you to translate content, comments, custom blocks, taxonomy terms, users and other <a href=":field_help" title="Field module help, with background on content entities">content entities</a>. Together with the modules <a href=":language">Language</a>, <a href=":config-trans">Configuration Translation</a>, and <a href=":locale">Interface Translation</a>, it allows you to build multilingual websites. For more information, see the <a href=":translation-entity">online documentation for the Content Translation module</a>.', [':locale' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', ['name' => 'locale']) : '#', ':config-trans' => (\Drupal::moduleHandler()->moduleExists('config_translation')) ? \Drupal::url('help.page', ['name' => 'config_translation']) : '#', ':language' => \Drupal::url('help.page', ['name' => 'language']), ':translation-entity' => 'https://www.drupal.org/documentation/modules/translation', ':field_help' => \Drupal::url('help.page', ['name' => 'field'])]) . '</p>';
29 $output .= '<h3>' . t('Uses') . '</h3>';
31 $output .= '<dt>' . t('Enabling translation') . '</dt>';
32 $output .= '<dd>' . t('In order to translate content, the website must have at least two <a href=":url">languages</a>. When that is the case, you can enable translation for the desired content entities on the <a href=":translation-entity">Content language</a> page. When enabling translation you can choose the default language for content and decide whether to show the language selection field on the content editing forms.', [':url' => \Drupal::url('entity.configurable_language.collection'), ':translation-entity' => \Drupal::url('language.content_settings_page'), ':language-help' => \Drupal::url('help.page', ['name' => 'language'])]) . '</dd>';
33 $output .= '<dt>' . t('Enabling field translation') . '</dt>';
34 $output .= '<dd>' . t('You can define which fields of a content entity can be translated. For example, you might want to translate the title and body field while leaving the image field untranslated. If you exclude a field from being translated, it will still show up in the content editing form, but any changes made to that field will be applied to <em>all</em> translations of that content.') . '</dd>';
35 $output .= '<dt>' . t('Translating content') . '</dt>';
36 $output .= '<dd>' . t('If translation is enabled you can translate a content entity via the Translate tab (or Translate link). The Translations page of a content entity gives an overview of the translation status for the current content and lets you add, edit, and delete its translations. This process is similar for every translatable content entity on your site.') . '</dd>';
37 $output .= '<dt>' . t('Changing the source language for a translation') . '</dt>';
38 $output .= '<dd>' . t('When you add a new translation, the original text you are translating is displayed in the edit form as the <em>source</em>. If at least one translation of the original content already exists when you add a new translation, you can choose either the original content (default) or one of the other translations as the source, using the select list in the Source language section. After saving the translation, the chosen source language is then listed on the Translate tab of the content.') . '</dd>';
39 $output .= '<dt>' . t('Setting status of translations') . '</dt>';
40 $output .= '<dd>' . t('If you edit a translation in one language you may want to set the status of the other translations as <em>out-of-date</em>. You can set this status by selecting the <em>Flag other translations as outdated</em> checkbox in the Translation section of the content editing form. The status will be visible on the Translations page.') . '</dd>';
44 case 'language.content_settings_page':
46 if (!\Drupal::languageManager()->isMultilingual()) {
47 $output .= '<p>' . t('Before you can translate content, there must be at least two languages added on the <a href=":url">languages administration</a> page.', [':url' => \Drupal::url('entity.configurable_language.collection')]) . '</p>';
54 * Implements hook_module_implements_alter().
56 function content_translation_module_implements_alter(&$implementations, $hook) {
58 // Move our hook_entity_type_alter() implementation to the end of the list.
59 case 'entity_type_alter':
60 $group = $implementations['content_translation'];
61 unset($implementations['content_translation']);
62 $implementations['content_translation'] = $group;
65 // Move our hook_entity_bundle_info_alter() implementation to the top of the
66 // list, so that any other hook implementation can rely on bundles being
67 // correctly marked as translatable.
68 case 'entity_bundle_info_alter':
69 $group = $implementations['content_translation'];
70 $implementations = ['content_translation' => $group] + $implementations;
76 * Implements hook_language_type_info_alter().
78 function content_translation_language_types_info_alter(array &$language_types) {
79 // Make content language negotiation configurable by removing the 'locked'
81 $language_types[LanguageInterface::TYPE_CONTENT]['locked'] = FALSE;
82 unset($language_types[LanguageInterface::TYPE_CONTENT]['fixed']);
86 * Implements hook_entity_type_alter().
88 * The content translation UI relies on the entity info to provide its features.
89 * See the documentation of hook_entity_type_build() in the Entity API
90 * documentation for more details on all the entity info keys that may be
93 * To make Content Translation automatically support an entity type some keys
94 * may need to be defined, but none of them is required unless the entity path
95 * is different from the usual /ENTITY_TYPE/{ENTITY_TYPE} pattern (for instance
96 * "/taxonomy/term/{taxonomy_term}"). Here are a list of those optional keys:
97 * - canonical: This key (in the 'links' entity info property) must be defined
98 * if the entity path is different from /ENTITY_TYPE/{ENTITY_TYPE}
99 * - translation: This key (in the 'handlers' entity annotation property)
100 * specifies the translation handler for the entity type. If an entity type is
101 * translatable and no translation handler is defined,
102 * \Drupal\content_translation\ContentTranslationHandler will be assumed.
103 * Every translation handler must implement
104 * \Drupal\content_translation\ContentTranslationHandlerInterface.
105 * - content_translation_ui_skip: By default, entity types that do not have a
106 * canonical link template cannot be enabled for translation. Setting this key
107 * to TRUE overrides that. When that key is set, the Content Translation
108 * module will not provide any UI for translating the entity type, and the
109 * entity type should implement its own UI. For instance, this is useful for
110 * entity types that are embedded into others for editing (which would not
111 * need a canonical link, but could still support translation).
112 * - content_translation_metadata: To implement its business logic the content
113 * translation UI relies on various metadata items describing the translation
114 * state. The default implementation is provided by
115 * \Drupal\content_translation\ContentTranslationMetadataWrapper, which is
116 * relying on one field for each metadata item (field definitions are provided
117 * by the translation handler). Entity types needing to customize this
118 * behavior can specify an alternative class through the
119 * 'content_translation_metadata' key in the entity type definition. Every
120 * content translation metadata wrapper needs to implement
121 * \Drupal\content_translation\ContentTranslationMetadataWrapperInterface.
123 * If the entity paths match the default pattern above and there is no need for
124 * an entity-specific translation handler, Content Translation will provide
125 * built-in support for the entity. However enabling translation for each
126 * translatable bundle will be required.
128 * @see \Drupal\Core\Entity\Annotation\EntityType
130 function content_translation_entity_type_alter(array &$entity_types) {
131 // Provide defaults for translation info.
132 /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
133 foreach ($entity_types as $entity_type) {
134 if ($entity_type->isTranslatable()) {
135 if (!$entity_type->hasHandlerClass('translation')) {
136 $entity_type->setHandlerClass('translation', 'Drupal\content_translation\ContentTranslationHandler');
138 if (!$entity_type->get('content_translation_metadata')) {
139 $entity_type->set('content_translation_metadata', 'Drupal\content_translation\ContentTranslationMetadataWrapper');
141 if (!$entity_type->getFormClass('content_translation_deletion')) {
142 $entity_type->setFormClass('content_translation_deletion', '\Drupal\content_translation\Form\ContentTranslationDeleteForm');
145 $translation = $entity_type->get('translation');
146 if (!$translation || !isset($translation['content_translation'])) {
147 $translation['content_translation'] = [];
150 if ($entity_type->hasLinkTemplate('canonical')) {
151 // Provide default route names for the translation paths.
152 if (!$entity_type->hasLinkTemplate('drupal:content-translation-overview')) {
153 $translations_path = $entity_type->getLinkTemplate('canonical') . '/translations';
154 $entity_type->setLinkTemplate('drupal:content-translation-overview', $translations_path);
155 $entity_type->setLinkTemplate('drupal:content-translation-add', $translations_path . '/add/{source}/{target}');
156 $entity_type->setLinkTemplate('drupal:content-translation-edit', $translations_path . '/edit/{language}');
157 $entity_type->setLinkTemplate('drupal:content-translation-delete', $translations_path . '/delete/{language}');
159 // @todo Remove this as soon as menu access checks rely on the
160 // controller. See https://www.drupal.org/node/2155787.
161 $translation['content_translation'] += [
162 'access_callback' => 'content_translation_translate_access',
165 $entity_type->set('translation', $translation);
168 $entity_type->addConstraint('ContentTranslationSynchronizedFields');
173 * Implements hook_entity_bundle_info_alter().
175 function content_translation_entity_bundle_info_alter(&$bundles) {
176 /** @var \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager */
177 $content_translation_manager = \Drupal::service('content_translation.manager');
178 foreach ($bundles as $entity_type_id => &$info) {
179 foreach ($info as $bundle => &$bundle_info) {
180 $bundle_info['translatable'] = $content_translation_manager->isEnabled($entity_type_id, $bundle);
181 if ($bundle_info['translatable'] && $content_translation_manager instanceof BundleTranslationSettingsInterface) {
182 $settings = $content_translation_manager->getBundleTranslationSettings($entity_type_id, $bundle);
183 // If pending revision support is enabled for this bundle, we need to
184 // hide untranslatable field widgets, otherwise changes in pending
185 // revisions might be overridden by changes in later default revisions.
186 $bundle_info['untranslatable_fields.default_translation_affected'] =
187 !empty($settings['untranslatable_fields_hide']) || ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $bundle);
194 * Implements hook_entity_base_field_info().
196 function content_translation_entity_base_field_info(EntityTypeInterface $entity_type) {
197 /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
198 $manager = \Drupal::service('content_translation.manager');
199 $entity_type_id = $entity_type->id();
200 if ($manager->isSupported($entity_type_id)) {
201 $definitions = $manager->getTranslationHandler($entity_type_id)->getFieldDefinitions();
202 $installed_storage_definitions = \Drupal::entityManager()->getLastInstalledFieldStorageDefinitions($entity_type_id);
203 // We return metadata storage fields whenever content translation is enabled
204 // or it was enabled before, so that we keep translation metadata around
205 // when translation is disabled.
206 // @todo Re-evaluate this approach and consider removing field storage
207 // definitions and the related field data if the entity type has no bundle
208 // enabled for translation.
209 // @see https://www.drupal.org/node/2907777
210 if ($manager->isEnabled($entity_type_id) || array_intersect_key($definitions, $installed_storage_definitions)) {
217 * Implements hook_field_info_alter().
219 * Content translation extends the @FieldType annotation with following key:
220 * - column_groups: contains information about the field type properties
221 * which columns should be synchronized across different translations and
222 * which are translatable. This is useful for instance to translate the
223 * "alt" and "title" textual elements of an image field, while keeping the
224 * same image on every translation. Each group has the following keys:
225 * - title: Title of the column group.
226 * - translatable: (optional) If the column group should be translatable by
227 * default, defaults to FALSE.
228 * - columns: (optional) A list of columns of this group. Defaults to the
229 * name of he group as the single column.
230 * - require_all_groups_for_translation: (optional) Set to TRUE to enforce
231 * that making this column group translatable requires all others to be
234 * @see Drupal\image\Plugin\Field\FieldType\ImageItem
236 function content_translation_field_info_alter(&$info) {
237 foreach ($info as $key => $settings) {
238 // Supply the column_groups key if it's not there.
239 if (empty($settings['column_groups'])) {
240 $info[$key]['column_groups'] = [];
246 * Implements hook_entity_operation().
248 function content_translation_entity_operation(EntityInterface $entity) {
250 if ($entity->hasLinkTemplate('drupal:content-translation-overview') && content_translation_translate_access($entity)->isAllowed()) {
251 $operations['translate'] = [
252 'title' => t('Translate'),
253 'url' => $entity->urlInfo('drupal:content-translation-overview'),
261 * Implements hook_views_data_alter().
263 function content_translation_views_data_alter(array &$data) {
264 // Add the content translation entity link definition to Views data for entity
265 // types having translation enabled.
266 $entity_types = \Drupal::entityManager()->getDefinitions();
267 /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
268 $manager = \Drupal::service('content_translation.manager');
269 foreach ($entity_types as $entity_type_id => $entity_type) {
270 $base_table = $entity_type->getBaseTable();
271 if (isset($data[$base_table]) && $entity_type->hasLinkTemplate('drupal:content-translation-overview') && $manager->isEnabled($entity_type_id)) {
272 $t_arguments = ['@entity_type_label' => $entity_type->getLabel()];
273 $data[$base_table]['translation_link'] = [
275 'title' => t('Link to translate @entity_type_label', $t_arguments),
276 'help' => t('Provide a translation link to the @entity_type_label.', $t_arguments),
277 'id' => 'content_translation_link',
285 * Implements hook_menu_links_discovered_alter().
287 function content_translation_menu_links_discovered_alter(array &$links) {
288 // Clarify where translation settings are located.
289 $links['language.content_settings_page']['title'] = new TranslatableMarkup('Content language and translation');
290 $links['language.content_settings_page']['description'] = new TranslatableMarkup('Configure language and translation support for content.');
294 * Access callback for the translation overview page.
296 * @param \Drupal\Core\Entity\EntityInterface $entity
297 * The entity whose translation overview should be displayed.
299 * @return \Drupal\Core\Access\AccessResultInterface
302 function content_translation_translate_access(EntityInterface $entity) {
303 $account = \Drupal::currentUser();
304 $condition = $entity instanceof ContentEntityInterface && $entity->access('view') &&
305 !$entity->getUntranslated()->language()->isLocked() && \Drupal::languageManager()->isMultilingual() && $entity->isTranslatable() &&
306 ($account->hasPermission('create content translations') || $account->hasPermission('update content translations') || $account->hasPermission('delete content translations'));
307 return AccessResult::allowedIf($condition)->cachePerPermissions()->addCacheableDependency($entity);
311 * Implements hook_form_alter().
313 function content_translation_form_alter(array &$form, FormStateInterface $form_state) {
314 $form_object = $form_state->getFormObject();
315 if (!($form_object instanceof ContentEntityFormInterface)) {
318 $entity = $form_object->getEntity();
319 $op = $form_object->getOperation();
321 // Let the content translation handler alter the content entity form. This can
322 // be the 'add' or 'edit' form. It also tries a 'default' form in case neither
323 // of the aforementioned forms are defined.
324 if ($entity instanceof ContentEntityInterface && $entity->isTranslatable() && count($entity->getTranslationLanguages()) > 1 && in_array($op, ['edit', 'add', 'default'], TRUE)) {
325 $controller = \Drupal::entityManager()->getHandler($entity->getEntityTypeId(), 'translation');
326 $controller->entityFormAlter($form, $form_state, $entity);
328 // @todo Move the following lines to the code generating the property form
329 // elements once we have an official #multilingual FAPI key.
330 $translations = $entity->getTranslationLanguages();
331 $form_langcode = $form_object->getFormLangcode($form_state);
333 // Handle fields shared between translations when there is at least one
334 // translation available or a new one is being created.
335 if (!$entity->isNew() && (!isset($translations[$form_langcode]) || count($translations) > 1)) {
336 foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
338 // Allow the widget to define if it should be treated as multilingual
339 // by respecting an already set #multilingual key.
340 if (isset($form[$field_name]) && !isset($form[$field_name]['#multilingual'])) {
341 $form[$field_name]['#multilingual'] = $definition->isTranslatable();
346 // The footer region, if defined, may contain multilingual widgets so we
347 // need to always display it.
348 if (isset($form['footer'])) {
349 $form['footer']['#multilingual'] = TRUE;
355 * Implements hook_language_fallback_candidates_OPERATION_alter().
357 * Performs language fallback for inaccessible translations.
359 function content_translation_language_fallback_candidates_entity_view_alter(&$candidates, $context) {
360 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
361 $entity = $context['data'];
362 $entity_type_id = $entity->getEntityTypeId();
363 /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
364 $manager = \Drupal::service('content_translation.manager');
365 if ($manager->isEnabled($entity_type_id, $entity->bundle())) {
366 $entity_type = $entity->getEntityType();
367 $permission = $entity_type->getPermissionGranularity() == 'bundle' ? $permission = "translate {$entity->bundle()} $entity_type_id" : "translate $entity_type_id";
368 $current_user = \Drupal::currentuser();
369 if (!$current_user->hasPermission('translate any entity') && !$current_user->hasPermission($permission)) {
370 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
371 $metadata = $manager->getTranslationMetadata($entity->getTranslation($langcode));
372 if (!$metadata->isPublished()) {
373 unset($candidates[$langcode]);
381 * Implements hook_entity_extra_field_info().
383 function content_translation_entity_extra_field_info() {
385 $bundle_info_service = \Drupal::service('entity_type.bundle.info');
386 foreach (\Drupal::entityManager()->getDefinitions() as $entity_type => $info) {
387 foreach ($bundle_info_service->getBundleInfo($entity_type) as $bundle => $bundle_info) {
388 if (\Drupal::service('content_translation.manager')->isEnabled($entity_type, $bundle)) {
389 $extra[$entity_type][$bundle]['form']['translation'] = [
390 'label' => t('Translation'),
391 'description' => t('Translation settings'),
402 * Implements hook_form_FORM_ID_alter() for 'field_config_edit_form'.
404 function content_translation_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state) {
405 $field = $form_state->getFormObject()->getEntity();
406 $bundle_is_translatable = \Drupal::service('content_translation.manager')->isEnabled($field->getTargetEntityTypeId(), $field->getTargetBundle());
408 $form['translatable'] = [
409 '#type' => 'checkbox',
410 '#title' => t('Users may translate this field'),
411 '#default_value' => $field->isTranslatable(),
413 '#disabled' => !$bundle_is_translatable,
414 '#access' => $field->getFieldStorageDefinition()->isTranslatable(),
417 // Provide helpful pointers for administrators.
418 if (\Drupal::currentUser()->hasPermission('administer content translation') && !$bundle_is_translatable) {
419 $toggle_url = \Drupal::url('language.content_settings_page', [], [
420 'query' => \Drupal::destination()->getAsArray(),
422 $form['translatable']['#description'] = t('To configure translation for this field, <a href=":language-settings-url">enable language support</a> for this type.', [
423 ':language-settings-url' => $toggle_url,
427 if ($field->isTranslatable()) {
428 module_load_include('inc', 'content_translation', 'content_translation.admin');
429 $element = content_translation_field_sync_widget($field);
431 $form['third_party_settings']['content_translation']['translation_sync'] = $element;
432 $form['third_party_settings']['content_translation']['translation_sync']['#weight'] = -10;
438 * Implements hook_entity_presave().
440 function content_translation_entity_presave(EntityInterface $entity) {
441 if ($entity instanceof ContentEntityInterface && $entity->isTranslatable() && !$entity->isNew()) {
442 /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
443 $manager = \Drupal::service('content_translation.manager');
444 if (!$manager->isEnabled($entity->getEntityTypeId(), $entity->bundle())) {
447 // If we are creating a new translation we need to use the source language
448 // as original language, since source values are the only ones available to
450 if (!isset($entity->original)) {
451 $entity->original = \Drupal::entityTypeManager()
452 ->getStorage($entity->entityType())->loadUnchanged($entity->id());
454 $langcode = $entity->language()->getId();
455 $source_langcode = !$entity->original->hasTranslation($langcode) ? $manager->getTranslationMetadata($entity)->getSource() : NULL;
456 \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $langcode, $source_langcode);
461 * Implements hook_element_info_alter().
463 function content_translation_element_info_alter(&$type) {
464 if (isset($type['language_configuration'])) {
465 $type['language_configuration']['#process'][] = 'content_translation_language_configuration_element_process';
470 * Returns a widget to enable content translation per entity bundle.
472 * Backward compatibility layer to support entities not using the language
473 * configuration form element.
475 * @todo Remove once all core entities have language configuration.
477 * @param string $entity_type
478 * The type of the entity being configured for translation.
479 * @param string $bundle
480 * The bundle of the entity being configured for translation.
482 * The configuration form array.
483 * @param \Drupal\Core\Form\FormStateInterface $form_state
484 * The current state of the form.
486 function content_translation_enable_widget($entity_type, $bundle, array &$form, FormStateInterface $form_state) {
487 $key = $form_state->get(['content_translation', 'key']);
488 $context = $form_state->get(['language', $key]) ?: [];
489 $context += ['entity_type' => $entity_type, 'bundle' => $bundle];
490 $form_state->set(['language', $key], $context);
491 $element = content_translation_language_configuration_element_process(['#name' => $key], $form_state, $form);
492 unset($element['content_translation']['#element_validate']);
497 * Process callback: Expands the language_configuration form element.
499 * @param array $element
503 * Processed language configuration element.
505 function content_translation_language_configuration_element_process(array $element, FormStateInterface $form_state, array &$form) {
506 if (empty($element['#content_translation_skip_alter']) && \Drupal::currentUser()->hasPermission('administer content translation')) {
507 $key = $element['#name'];
508 $form_state->set(['content_translation', 'key'], $key);
509 $context = $form_state->get(['language', $key]);
511 $element['content_translation'] = [
512 '#type' => 'checkbox',
513 '#title' => t('Enable translation'),
514 // For new bundle, we don't know the bundle name yet,
515 // default to no translatability.
516 '#default_value' => $context['bundle'] ? \Drupal::service('content_translation.manager')->isEnabled($context['entity_type'], $context['bundle']) : FALSE,
517 '#element_validate' => ['content_translation_language_configuration_element_validate'],
520 $submit_name = isset($form['actions']['save_continue']) ? 'save_continue' : 'submit';
521 // Only add the submit handler on the submit button if the #submit property
522 // is already available, otherwise this breaks the form submit function.
523 if (isset($form['actions'][$submit_name]['#submit'])) {
524 $form['actions'][$submit_name]['#submit'][] = 'content_translation_language_configuration_element_submit';
527 $form['#submit'][] = 'content_translation_language_configuration_element_submit';
534 * Form validation handler for element added with content_translation_language_configuration_element_process().
536 * Checks whether translation can be enabled: if language is set to one of the
537 * special languages and language selector is not hidden, translation cannot be
540 * @see content_translation_language_configuration_element_submit()
542 function content_translation_language_configuration_element_validate($element, FormStateInterface $form_state, array $form) {
543 $key = $form_state->get(['content_translation', 'key']);
544 $values = $form_state->getValue($key);
545 if (!$values['language_alterable'] && $values['content_translation'] && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
546 foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $language) {
547 $locked_languages[] = $language->getName();
549 // @todo Set the correct form element name as soon as the element parents
550 // are correctly set. We should be using NestedArray::getValue() but for
552 $form_state->setErrorByName('', t('"Show language selector" is not compatible with translating content that has default language: %choice. Either do not hide the language selector or pick a specific language.', ['%choice' => $locked_languages[$values['langcode']]]));
557 * Form submission handler for element added with content_translation_language_configuration_element_process().
559 * Stores the content translation settings.
561 * @see content_translation_language_configuration_element_validate()
563 function content_translation_language_configuration_element_submit(array $form, FormStateInterface $form_state) {
564 $key = $form_state->get(['content_translation', 'key']);
565 $context = $form_state->get(['language', $key]);
566 $enabled = $form_state->getValue([$key, 'content_translation']);
568 if (\Drupal::service('content_translation.manager')->isEnabled($context['entity_type'], $context['bundle']) != $enabled) {
569 \Drupal::service('content_translation.manager')->setEnabled($context['entity_type'], $context['bundle'], $enabled);
570 \Drupal::entityManager()->clearCachedDefinitions();
571 \Drupal::service('router.builder')->setRebuildNeeded();
576 * Implements hook_form_FORM_ID_alter() for language_content_settings_form().
578 function content_translation_form_language_content_settings_form_alter(array &$form, FormStateInterface $form_state) {
579 module_load_include('inc', 'content_translation', 'content_translation.admin');
580 _content_translation_form_language_content_settings_form_alter($form, $form_state);
584 * Implements hook_preprocess_HOOK() for language-content-settings-table.html.twig.
586 function content_translation_preprocess_language_content_settings_table(&$variables) {
587 module_load_include('inc', 'content_translation', 'content_translation.admin');
588 _content_translation_preprocess_language_content_settings_table($variables);
592 * Implements hook_page_attachments().
594 function content_translation_page_attachments(&$page) {
595 $route_match = \Drupal::routeMatch();
597 // If the current route has no parameters, return.
598 if (!($route = $route_match->getRouteObject()) || !($parameters = $route->getOption('parameters'))) {
602 // Determine if the current route represents an entity.
603 foreach ($parameters as $name => $options) {
604 if (!isset($options['type']) || strpos($options['type'], 'entity:') !== 0) {
608 $entity = $route_match->getParameter($name);
609 if ($entity instanceof ContentEntityInterface && $entity->hasLinkTemplate('canonical')) {
610 // Current route represents a content entity. Build hreflang links.
611 foreach ($entity->getTranslationLanguages() as $language) {
612 $url = $entity->toUrl('canonical')
613 ->setOption('language', $language)
616 $page['#attached']['html_head_link'][] = [
618 'rel' => 'alternate',
619 'hreflang' => $language->getId(),
626 // Since entity was found, no need to iterate further.