content_translation.admin.inc 17.2 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * The content translation administration forms.
6 7
 */

8
use Drupal\content_translation\BundleTranslationSettingsInterface;
9
use Drupal\content_translation\ContentTranslationManager;
10
use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
11
use Drupal\Core\Entity\ContentEntityTypeInterface;
12
use Drupal\Core\Entity\EntityTypeInterface;
13
use Drupal\Core\Field\FieldDefinitionInterface;
14
use Drupal\Core\Field\FieldStorageDefinitionInterface;
15
use Drupal\Core\Form\FormStateInterface;
16
use Drupal\Core\Language\LanguageInterface;
17
use Drupal\Core\Render\Element;
18

19
/**
20
 * Returns a form element to configure field synchronization.
21
 *
22
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field
23
 *   A field definition object.
24 25 26
 * @param string $element_name
 *   (optional) The element name, which is added to drupalSettings so that
 *   javascript can manipulate the form element.
27 28 29 30
 *
 * @return array
 *   A form element to configure field synchronization.
 */
31
function content_translation_field_sync_widget(FieldDefinitionInterface $field, $element_name = 'third_party_settings[content_translation][translation_sync]') {
32 33
  // No way to store field sync information on this field.
  if (!($field instanceof ThirdPartySettingsInterface)) {
34
    return [];
35
  }
36

37
  $element = [];
38 39
  $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($field->getType());
  $column_groups = $definition['column_groups'];
40
  if (!empty($column_groups) && count($column_groups) > 1) {
41 42 43
    $options = [];
    $default = [];
    $require_all_groups_for_translation = [];
44

45
    foreach ($column_groups as $group => $info) {
46 47
      $options[$group] = $info['label'];
      $default[$group] = !empty($info['translatable']) ? $group : FALSE;
48 49 50
      if (!empty($info['require_all_groups_for_translation'])) {
        $require_all_groups_for_translation[] = $group;
      }
51 52
    }

53
    $default = $field->getThirdPartySetting('content_translation', 'translation_sync', $default);
54

55
    $element = [
56 57 58
      '#type' => 'checkboxes',
      '#title' => t('Translatable elements'),
      '#options' => $options,
59
      '#default_value' => $default,
60
    ];
61 62 63 64 65 66 67

    if ($require_all_groups_for_translation) {
      // The actual checkboxes are sometimes rendered separately and the parent
      // element is ignored. Attach to the first option to ensure that this
      // does not get lost.
      $element[key($options)]['#attached']['drupalSettings']['contentTranslationDependentOptions'] = [
        'dependent_selectors' => [
68
          $element_name => $require_all_groups_for_translation,
69 70 71 72
        ],
      ];
      $element[key($options)]['#attached']['library'][] = 'content_translation/drupal.content_translation.admin';
    }
73 74 75 76 77 78 79
  }

  return $element;
}

/**
 * (proxied) Implements hook_form_FORM_ID_alter().
80
 */
81
function _content_translation_form_language_content_settings_form_alter(array &$form, FormStateInterface $form_state) {
82 83
  // Inject into the content language settings the translation settings if the
  // user has the required permission.
84
  if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
85 86 87
    return;
  }

88
  /** @var \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager */
89
  $content_translation_manager = \Drupal::service('content_translation.manager');
90
  $default = $form['entity_types']['#default_value'];
91
  foreach ($default as $entity_type_id => $enabled) {
92
    $default[$entity_type_id] = $enabled || $content_translation_manager->isEnabled($entity_type_id) ? $entity_type_id : FALSE;
93 94 95
  }
  $form['entity_types']['#default_value'] = $default;

96
  $form['#attached']['library'][] = 'content_translation/drupal.content_translation.admin';
97

98
  $entity_manager = Drupal::entityManager();
99
  $bundle_info_service = \Drupal::service('entity_type.bundle.info');
100
  foreach ($form['#labels'] as $entity_type_id => $label) {
101
    $entity_type = $entity_manager->getDefinition($entity_type_id);
102
    $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $entity_manager->getFieldStorageDefinitions($entity_type_id) : [];
103

104
    $entity_type_translatable = $content_translation_manager->isSupported($entity_type_id);
105
    foreach ($bundle_info_service->getBundleInfo($entity_type_id) as $bundle => $bundle_info) {
106 107
      // Here we do not want the widget to be altered and hold also the "Enable
      // translation" checkbox, which would be redundant. Hence we add this key
108 109
      // to be able to skip alterations. Alter the title and display the message
      // about UI integration.
110
      $form['settings'][$entity_type_id][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE;
111
      if (!$entity_type_translatable) {
112
        $form['settings'][$entity_type_id]['#title'] = t('@label (Translation is not supported).', ['@label' => $entity_type->getLabel()]);
113 114
        continue;
      }
115

116 117 118
      // Displayed the "shared fields widgets" toggle.
      if ($content_translation_manager instanceof BundleTranslationSettingsInterface) {
        $settings = $content_translation_manager->getBundleTranslationSettings($entity_type_id, $bundle);
119
        $force_hidden = ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $bundle);
120 121 122
        $form['settings'][$entity_type_id][$bundle]['settings']['content_translation']['untranslatable_fields_hide'] = [
          '#type' => 'checkbox',
          '#title' => t('Hide non translatable fields on translation forms'),
123 124 125
          '#default_value' => $force_hidden || !empty($settings['untranslatable_fields_hide']),
          '#disabled' => $force_hidden,
          '#description' => $force_hidden ? t('Moderated content requires non-translatable fields to be edited in the original language form.') : '',
126 127 128 129 130 131 132 133 134 135
          '#states' => [
            'visible' => [
              ':input[name="settings[' . $entity_type_id . '][' . $bundle . '][translatable]"]' => [
                'checked' => TRUE,
              ],
            ],
          ],
        ];
      }

136 137 138
      $fields = $entity_manager->getFieldDefinitions($entity_type_id, $bundle);
      if ($fields) {
        foreach ($fields as $field_name => $definition) {
139
          if ($definition->isComputed() || (!empty($storage_definitions[$field_name]) && _content_translation_is_field_translatability_configurable($entity_type, $storage_definitions[$field_name]))) {
140
            $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = [
141 142 143
              '#label' => $definition->getLabel(),
              '#type' => 'checkbox',
              '#default_value' => $definition->isTranslatable(),
144
            ];
145
            // Display the column translatability configuration widget.
146
            $column_element = content_translation_field_sync_widget($definition, "settings[{$entity_type_id}][{$bundle}][columns][{$field_name}]");
147 148 149 150 151 152 153 154
            if ($column_element) {
              $form['settings'][$entity_type_id][$bundle]['columns'][$field_name] = $column_element;
            }
          }
        }
        if (!empty($form['settings'][$entity_type_id][$bundle]['fields'])) {
          // Only show the checkbox to enable translation if the bundles in the
          // entity might have fields and if there are fields to translate.
155
          $form['settings'][$entity_type_id][$bundle]['translatable'] = [
156
            '#type' => 'checkbox',
157
            '#default_value' => $content_translation_manager->isEnabled($entity_type_id, $bundle),
158
          ];
159
        }
160 161 162
      }
    }
  }
163

164 165
  $form['#validate'][] = 'content_translation_form_language_content_settings_validate';
  $form['#submit'][] = 'content_translation_form_language_content_settings_submit';
166
}
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
/**
 * Checks whether translatability should be configurable for a field.
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $definition
 *   The field storage definition.
 *
 * @return bool
 *   TRUE if field translatability can be configured, FALSE otherwise.
 *
 * @internal
 */
function _content_translation_is_field_translatability_configurable(EntityTypeInterface $entity_type, FieldStorageDefinitionInterface $definition) {
  // Allow to configure only fields supporting multilingual storage. We skip our
  // own fields as they are always translatable. Additionally we skip a set of
  // well-known fields implementing entity system business logic.
  return
    $definition->isTranslatable() &&
    $definition->getProvider() != 'content_translation' &&
    !in_array($definition->getName(), [$entity_type->getKey('langcode'), $entity_type->getKey('default_langcode'), 'revision_translation_affected']);
}
190

191 192 193
/**
 * (proxied) Implements hook_preprocess_HOOK();
 */
194
function _content_translation_preprocess_language_content_settings_table(&$variables) {
195 196
  // Alter the 'build' variable injecting the translation settings if the user
  // has the required permission.
197
  if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
198 199 200 201 202 203
    return;
  }

  $element = $variables['element'];
  $build = &$variables['build'];

204 205
  array_unshift($build['#header'], ['data' => t('Translatable'), 'class' => ['translatable']]);
  $rows = [];
206

207
  foreach (Element::children($element) as $bundle) {
208
    $field_names = !empty($element[$bundle]['fields']) ? Element::children($element[$bundle]['fields']) : [];
209 210 211
    if (!empty($element[$bundle]['translatable'])) {
      $checkbox_id = $element[$bundle]['translatable']['#id'];
    }
212 213
    $rows[$bundle] = $build['#rows'][$bundle];

214
    if (!empty($element[$bundle]['translatable'])) {
215
      $translatable = [
216
        'data' => $element[$bundle]['translatable'],
217 218
        'class' => ['translatable'],
      ];
219
      array_unshift($rows[$bundle]['data'], $translatable);
220

221 222 223
      $rows[$bundle]['data'][1]['data']['#prefix'] = '<label for="' . $checkbox_id . '">';
    }
    else {
224
      $translatable = [
225
        'data' => t('N/A'),
226 227
        'class' => ['untranslatable'],
      ];
228 229
      array_unshift($rows[$bundle]['data'], $translatable);
    }
230 231 232

    foreach ($field_names as $field_name) {
      $field_element = &$element[$bundle]['fields'][$field_name];
233 234 235
      $rows[] = [
        'data' => [
          [
236
            'data' => \Drupal::service('renderer')->render($field_element),
237 238 239 240
            'class' => ['translatable'],
          ],
          [
            'data' => [
241 242
              '#prefix' => '<label for="' . $field_element['#id'] . '">',
              '#suffix' => '</label>',
243
              'bundle' => [
244
                '#prefix' => '<span class="visually-hidden">',
245
                '#suffix' => '</span> ',
246
                '#plain_text' => $element[$bundle]['settings']['#label'],
247 248
              ],
              'field' => [
249
                '#plain_text' => $field_element['#label'],
250 251 252 253 254
              ],
            ],
            'class' => ['field'],
          ],
          [
255
            'data' => '',
256 257 258 259 260
            'class' => ['operations'],
          ],
        ],
        'class' => ['field-settings'],
      ];
261 262 263

      if (!empty($element[$bundle]['columns'][$field_name])) {
        $column_element = &$element[$bundle]['columns'][$field_name];
264
        foreach (Element::children($column_element) as $key) {
265 266
          $column_label = $column_element[$key]['#title'];
          unset($column_element[$key]['#title']);
267 268 269
          $rows[] = [
            'data' => [
              [
270
                'data' => \Drupal::service('renderer')->render($column_element[$key]),
271 272 273 274
                'class' => ['translatable'],
              ],
              [
                'data' => [
275 276
                  '#prefix' => '<label for="' . $column_element[$key]['#id'] . '">',
                  '#suffix' => '</label>',
277
                  'bundle' => [
278
                    '#prefix' => '<span class="visually-hidden">',
279
                    '#suffix' => '</span> ',
280
                    '#plain_text' => $element[$bundle]['settings']['#label'],
281 282
                  ],
                  'field' => [
283
                    '#prefix' => '<span class="visually-hidden">',
284
                    '#suffix' => '</span> ',
285
                    '#plain_text' => $field_element['#label'],
286 287
                  ],
                  'columns' => [
288
                    '#plain_text' => $column_label,
289 290 291 292 293
                  ],
                ],
                'class' => ['column'],
              ],
              [
294
                'data' => '',
295 296 297 298 299
                'class' => ['operations'],
              ],
            ],
            'class' => ['column-settings'],
          ];
300 301 302 303 304 305 306 307
        }
      }
    }
  }

  $build['#rows'] = $rows;
}

308
/**
309
 * Form validation handler for content_translation_admin_settings_form().
310
 *
311
 * @see content_translation_admin_settings_form_submit()
312
 */
313
function content_translation_form_language_content_settings_validate(array $form, FormStateInterface $form_state) {
314
  $settings = &$form_state->getValue('settings');
315 316 317 318 319 320 321
  foreach ($settings as $entity_type => $entity_settings) {
    foreach ($entity_settings as $bundle => $bundle_settings) {
      if (!empty($bundle_settings['translatable'])) {
        $name = "settings][$entity_type][$bundle][translatable";

        $translatable_fields = isset($settings[$entity_type][$bundle]['fields']) ? array_filter($settings[$entity_type][$bundle]['fields']) : FALSE;
        if (empty($translatable_fields)) {
322
          $t_args = ['%bundle' => $form['settings'][$entity_type][$bundle]['settings']['#label']];
323
          $form_state->setErrorByName($name, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args));
324 325 326
        }

        $values = $bundle_settings['settings']['language'];
327
        if (empty($values['language_alterable']) && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
328
          foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $language) {
329
            $locked_languages[] = $language->getName();
330
          }
331
          $form_state->setErrorByName($name, t('Translation is not supported if language is always one of: @locked_languages', ['@locked_languages' => implode(', ', $locked_languages)]));
332 333 334 335 336 337 338
        }
      }
    }
  }
}

/**
339
 * Form submission handler for content_translation_admin_settings_form().
340
 *
341
 * @see content_translation_admin_settings_form_validate()
342
 */
343
function content_translation_form_language_content_settings_submit(array $form, FormStateInterface $form_state) {
344 345
  /** @var \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager */
  $content_translation_manager = \Drupal::service('content_translation.manager');
346 347
  $entity_types = $form_state->getValue('entity_types');
  $settings = &$form_state->getValue('settings');
348 349 350 351

  // If an entity type is not translatable all its bundles and fields must be
  // marked as non-translatable. Similarly, if a bundle is made non-translatable
  // all of its fields will be not translatable.
352 353
  foreach ($settings as $entity_type_id => &$entity_settings) {
    foreach ($entity_settings as $bundle => &$bundle_settings) {
354
      $fields = \Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle);
355
      if (!empty($bundle_settings['translatable'])) {
356
        $bundle_settings['translatable'] = $bundle_settings['translatable'] && $entity_types[$entity_type_id];
357
      }
358 359
      if (!empty($bundle_settings['fields'])) {
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
360
          $translatable = $translatable && $bundle_settings['translatable'];
361 362 363
          // If we have column settings and no column is translatable, no point
          // in making the field translatable.
          if (isset($bundle_settings['columns'][$field_name]) && !array_filter($bundle_settings['columns'][$field_name])) {
364
            $translatable = FALSE;
365
          }
366 367 368 369 370
          $field_config = $fields[$field_name]->getConfig($bundle);
          if ($field_config->isTranslatable() != $translatable) {
            $field_config
              ->setTranslatable($translatable)
              ->save();
371
          }
372 373
        }
      }
374 375
      if (isset($bundle_settings['translatable'])) {
        // Store whether a bundle has translation enabled or not.
376 377 378 379 380 381
        $content_translation_manager->setEnabled($entity_type_id, $bundle, $bundle_settings['translatable']);

        // Store any other bundle settings.
        if ($content_translation_manager instanceof BundleTranslationSettingsInterface) {
          $content_translation_manager->setBundleTranslationSettings($entity_type_id, $bundle, $bundle_settings['settings']['content_translation']);
        }
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

        // Save translation_sync settings.
        if (!empty($bundle_settings['columns'])) {
          foreach ($bundle_settings['columns'] as $field_name => $column_settings) {
            $field_config = $fields[$field_name]->getConfig($bundle);
            if ($field_config->isTranslatable()) {
              $field_config->setThirdPartySetting('content_translation', 'translation_sync', $column_settings);
            }
            // If the field does not have translatable enabled we need to reset
            // the sync settings to their defaults.
            else {
              $field_config->unsetThirdPartySetting('content_translation', 'translation_sync');
            }
            $field_config->save();
          }
        }
      }
399 400
    }
  }
401

402 403 404
  // Ensure entity and menu router information are correctly rebuilt.
  \Drupal::entityManager()->clearCachedDefinitions();
  \Drupal::service('router.builder')->setRebuildNeeded();
405
}