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

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

8
use Drupal\Component\Utility\String;
9
use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
10
use Drupal\Core\Entity\ContentEntityTypeInterface;
11
use Drupal\Core\Field\FieldDefinitionInterface;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Language\LanguageInterface;
14
use Drupal\Core\Render\Element;
15
use Drupal\field\FieldInstanceConfigInterface;
16

17
/**
18
 * Returns a form element to configure field synchronization.
19
 *
20
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field
21
 *   A field definition object.
22 23 24 25
 *
 * @return array
 *   A form element to configure field synchronization.
 */
26
function content_translation_field_sync_widget(FieldDefinitionInterface $field) {
27 28 29 30
  // No way to store field sync information on this field.
  if (!($field instanceof ThirdPartySettingsInterface)) {
    return array();
  }
31

32
  $element = array();
33 34
  $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($field->getType());
  $column_groups = $definition['column_groups'];
35
  if (!empty($column_groups) && count($column_groups) > 1) {
36 37 38
    $options = array();
    $default = array();

39
    foreach ($column_groups as $group => $info) {
40 41 42 43
      $options[$group] = $info['label'];
      $default[$group] = !empty($info['translatable']) ? $group : FALSE;
    }

44 45
    $settings = array('dependent_selectors' => array('instance[third_party_settings][content_translation][translation_sync]' => array('file')));
    $default = $field->getThirdPartySetting('content_translation', 'translation_sync', $default);
46

47 48 49 50
    $element = array(
      '#type' => 'checkboxes',
      '#title' => t('Translatable elements'),
      '#options' => $options,
51
      '#default_value' => $default,
52
      '#attached' => array(
53
        'library' => array(
54
          'content_translation/drupal.content_translation.admin',
55
        ),
56
        'js' => array(
57
          array('data' => array('contentTranslationDependentOptions' => $settings), 'type' => 'setting'),
58 59
        ),
      ),
60 61 62 63 64 65 66 67
    );
  }

  return $element;
}

/**
 * (proxied) Implements hook_form_FORM_ID_alter().
68
 */
69
function _content_translation_form_language_content_settings_form_alter(array &$form, FormStateInterface $form_state) {
70 71
  // Inject into the content language settings the translation settings if the
  // user has the required permission.
72
  if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
73 74 75 76
    return;
  }

  $default = $form['entity_types']['#default_value'];
77 78
  foreach ($default as $entity_type_id => $enabled) {
    $default[$entity_type_id] = $enabled || content_translation_enabled($entity_type_id) ? $entity_type_id : FALSE;
79 80 81
  }
  $form['entity_types']['#default_value'] = $default;

82
  $form['#attached']['library'][] = 'content_translation/drupal.content_translation.admin';
83
  $form['#attached']['js'][] = array('data' => drupal_get_path('module', 'content_translation') . '/content_translation.admin.js', 'type' => 'file');
84

85
  $dependent_options_settings = array();
86
  $entity_manager = Drupal::entityManager();
87
  foreach ($form['#labels'] as $entity_type_id => $label) {
88 89 90
    $entity_type = $entity_manager->getDefinition($entity_type_id);
    $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $entity_manager->getFieldStorageDefinitions($entity_type_id) : array();

91
    foreach (entity_get_bundles($entity_type_id) as $bundle => $bundle_info) {
92 93 94
      // 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
      // to be able to skip alterations.
95
      $form['settings'][$entity_type_id][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE;
96

97 98
      // Only show the checkbox to enable translation if the bundles in the
      // entity might have fields and if there are fields to translate.
99 100
      if ($entity_type->isFieldable()) {
        $fields = $entity_manager->getFieldDefinitions($entity_type_id, $bundle);
101
        if ($fields) {
102
          $form['settings'][$entity_type_id][$bundle]['translatable'] = array(
103
            '#type' => 'checkbox',
104
            '#default_value' => content_translation_enabled($entity_type_id, $bundle),
105 106
          );

107
          foreach ($fields as $field_name => $definition) {
108 109
            // Allow to configure only fields supporting multilingual storage.
            if (!empty($storage_definitions[$field_name]) && $storage_definitions[$field_name]->isTranslatable()) {
110
              $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = array(
111
                '#label' => $definition->getLabel(),
112
                '#type' => 'checkbox',
113
                '#default_value' => $definition->isTranslatable(),
114
              );
115
              // Display the column translatability configuration widget.
116 117 118 119 120 121
              $column_element = content_translation_field_sync_widget($definition);
              if ($column_element) {
                $form['settings'][$entity_type_id][$bundle]['columns'][$field_name] = $column_element;
                // @todo This should not concern only files.
                if (isset($column_element['#options']['file'])) {
                  $dependent_options_settings["settings[{$entity_type_id}][{$bundle}][columns][{$field_name}]"] = array('file');
122
                }
123 124
              }
            }
125
          }
126
        }
127 128 129
      }
    }
  }
130

131
  $settings = array('dependent_selectors' => $dependent_options_settings);
132 133 134
  $form['#attached']['js'][] = array('data' => array('contentTranslationDependentOptions' => $settings), 'type' => 'setting');
  $form['#validate'][] = 'content_translation_form_language_content_settings_validate';
  $form['#submit'][] = 'content_translation_form_language_content_settings_submit';
135 136
}

137 138 139
/**
 * (proxied) Implements hook_preprocess_HOOK();
 */
140
function _content_translation_preprocess_language_content_settings_table(&$variables) {
141 142
  // Alter the 'build' variable injecting the translation settings if the user
  // has the required permission.
143
  if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
144 145 146 147 148 149 150 151 152
    return;
  }

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

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

153 154
  foreach (Element::children($element) as $bundle) {
    $field_names = !empty($element[$bundle]['fields']) ? Element::children($element[$bundle]['fields']) : array();
155 156 157
    if (!empty($element[$bundle]['translatable'])) {
      $checkbox_id = $element[$bundle]['translatable']['#id'];
    }
158 159
    $rows[$bundle] = $build['#rows'][$bundle];

160 161 162 163 164 165
    if (!empty($element[$bundle]['translatable'])) {
      $translatable = array(
        'data' => $element[$bundle]['translatable'],
        'class' => array('translatable'),
      );
      array_unshift($rows[$bundle]['data'], $translatable);
166

167 168 169 170 171 172 173 174
      $rows[$bundle]['data'][1]['data']['#prefix'] = '<label for="' . $checkbox_id . '">';
    }
    else {
      $translatable = array(
        'class' => array('untranslatable'),
      );
      array_unshift($rows[$bundle]['data'], $translatable);
    }
175 176 177 178 179 180 181 182 183 184 185 186 187 188

    foreach ($field_names as $field_name) {
      $field_element = &$element[$bundle]['fields'][$field_name];
      $rows[] = array(
        'data' => array(
          array(
            'data' => drupal_render($field_element),
            'class' => array('translatable'),
          ),
          array(
            'data' => array(
              '#prefix' => '<label for="' . $field_element['#id'] . '">',
              '#suffix' => '</label>',
              'bundle' => array(
189
                '#prefix' => '<span class="visually-hidden">',
190
                '#suffix' => '</span> ',
191
                '#markup' => String::checkPlain($element[$bundle]['settings']['#label']),
192 193
              ),
              'field' => array(
194
                '#markup' => String::checkPlain($field_element['#label']),
195 196 197 198 199 200 201 202 203 204 205 206 207 208
              ),
            ),
            'class' => array('field'),
          ),
          array(
            'data' => '',
            'class' => array('operations'),
          ),
        ),
        'class' => array('field-settings'),
      );

      if (!empty($element[$bundle]['columns'][$field_name])) {
        $column_element = &$element[$bundle]['columns'][$field_name];
209
        foreach (Element::children($column_element) as $key) {
210 211 212 213 214 215 216 217 218 219 220 221 222
          $column_label = $column_element[$key]['#title'];
          unset($column_element[$key]['#title']);
          $rows[] = array(
            'data' => array(
              array(
                'data' => drupal_render($column_element[$key]),
                'class' => array('translatable'),
              ),
              array(
                'data' => array(
                  '#prefix' => '<label for="' . $column_element[$key]['#id'] . '">',
                  '#suffix' => '</label>',
                  'bundle' => array(
223
                    '#prefix' => '<span class="visually-hidden">',
224
                    '#suffix' => '</span> ',
225
                    '#markup' => String::checkPlain($element[$bundle]['settings']['#label']),
226 227
                  ),
                  'field' => array(
228
                    '#prefix' => '<span class="visually-hidden">',
229
                    '#suffix' => '</span> ',
230
                    '#markup' => String::checkPlain($field_element['#label']),
231 232
                  ),
                  'columns' => array(
233
                    '#markup' => String::checkPlain($column_label),
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                  ),
                ),
                'class' => array('column'),
              ),
              array(
                'data' => '',
                'class' => array('operations'),
              ),
            ),
            'class' => array('column-settings'),
          );
        }
      }
    }
  }

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

253
/**
254
 * Form validation handler for content_translation_admin_settings_form().
255
 *
256
 * @see content_translation_admin_settings_form_submit()
257
 */
258
function content_translation_form_language_content_settings_validate(array $form, FormStateInterface $form_state) {
259
  $settings = &$form_state->getValue('settings');
260 261 262 263 264 265 266 267
  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)) {
          $t_args = array('%bundle' => $form['settings'][$entity_type][$bundle]['settings']['#label']);
268
          $form_state->setErrorByName($name, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args));
269 270 271
        }

        $values = $bundle_settings['settings']['language'];
272
        if (empty($values['language_show']) && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
273
          foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $language) {
274 275
            $locked_languages[] = $language->name;
          }
276
          $form_state->setErrorByName($name, t('Translation is not supported if language is always one of: @locked_languages', array('@locked_languages' => implode(', ', $locked_languages))));
277 278 279 280 281 282 283
        }
      }
    }
  }
}

/**
284
 * Form submission handler for content_translation_admin_settings_form().
285
 *
286
 * @see content_translation_admin_settings_form_validate()
287
 */
288
function content_translation_form_language_content_settings_submit(array $form, FormStateInterface $form_state) {
289 290
  $entity_types = $form_state->getValue('entity_types');
  $settings = &$form_state->getValue('settings');
291 292 293 294

  // 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.
295 296
  foreach ($settings as $entity_type_id => &$entity_settings) {
    foreach ($entity_settings as $bundle => &$bundle_settings) {
297
      $fields = \Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle);
298
      if (!empty($bundle_settings['translatable'])) {
299
        $bundle_settings['translatable'] = $bundle_settings['translatable'] && $entity_types[$entity_type_id];
300
      }
301 302
      if (!empty($bundle_settings['fields'])) {
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
303
          $translatable = $translatable && $bundle_settings['translatable'];
304 305 306
          // 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])) {
307
            $translatable = FALSE;
308
          }
309 310 311 312 313
          $field_config = $fields[$field_name]->getConfig($bundle);
          if ($field_config->isTranslatable() != $translatable) {
            $field_config
              ->setTranslatable($translatable)
              ->save();
314
          }
315 316
        }
      }
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
      if (isset($bundle_settings['translatable'])) {
        // Store whether a bundle has translation enabled or not.
        content_translation_set_config($entity_type_id, $bundle, 'enabled', $bundle_settings['translatable']);

        // 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();
          }
        }
      }
337 338 339
    }
  }

340 341 342 343
  // Ensure entity and menu router information are correctly rebuilt.
  \Drupal::entityManager()->clearCachedDefinitions();
  \Drupal::service('router.builder')->setRebuildNeeded();

344
  drupal_set_message(t('Settings successfully updated.'));
345
}