content_translation.admin.inc 15 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\Entity\EntityInterface;
10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Language\Language;
12
use Drupal\field\Field as FieldService;
13

14
/**
15
 * Returns a form element to configure field synchronization.
16
 *
17
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field
18
 *   A field definition object.
19 20 21 22
 *
 * @return array
 *   A form element to configure field synchronization.
 */
23
function content_translation_field_sync_widget(FieldDefinitionInterface $field) {
24 25
  $element = array();

26
  $column_groups = $field->getSetting('column_groups');
27
  if (!empty($column_groups) && count($column_groups) > 1) {
28 29 30
    $options = array();
    $default = array();

31
    foreach ($column_groups as $group => $info) {
32 33 34 35
      $options[$group] = $info['label'];
      $default[$group] = !empty($info['translatable']) ? $group : FALSE;
    }

36 37
    $settings = array('dependent_selectors' => array('instance[settings][translation_sync]' => array('file')));

38
    $translation_sync = $field->getSetting('translation_sync');
39 40 41 42
    $element = array(
      '#type' => 'checkboxes',
      '#title' => t('Translatable elements'),
      '#options' => $options,
43
      '#default_value' => !empty($translation_sync) ? $translation_sync : $default,
44
      '#attached' => array(
45
        'library' => array(
46
          array('content_translation', 'drupal.content_translation.admin'),
47
        ),
48
        'js' => array(
49
          array('data' => array('contentTranslationDependentOptions' => $settings), 'type' => 'setting'),
50 51
        ),
      ),
52 53 54 55 56 57 58 59
    );
  }

  return $element;
}

/**
 * (proxied) Implements hook_form_FORM_ID_alter().
60
 */
61
function _content_translation_form_language_content_settings_form_alter(array &$form, array &$form_state) {
62 63
  // Inject into the content language settings the translation settings if the
  // user has the required permission.
64
  if (!user_access('administer content translation')) {
65 66 67 68
    return;
  }

  $default = $form['entity_types']['#default_value'];
69 70
  foreach ($default as $entity_type_id => $enabled) {
    $default[$entity_type_id] = $enabled || content_translation_enabled($entity_type_id) ? $entity_type_id : FALSE;
71 72 73
  }
  $form['entity_types']['#default_value'] = $default;

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

77
  $dependent_options_settings = array();
78
  $entity_manager = Drupal::entityManager();
79 80 81
  foreach ($form['#labels'] as $entity_type_id => $label) {
    $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
    foreach (entity_get_bundles($entity_type_id) as $bundle => $bundle_info) {
82 83 84
      // 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.
85
      $form['settings'][$entity_type_id][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE;
86

87 88
      // Only show the checkbox to enable translation if the bundles in the
      // entity might have fields and if there are fields to translate.
89 90
      if ($entity_type->isFieldable()) {
        $fields = $entity_manager->getFieldDefinitions($entity_type_id, $bundle);
91
        if ($fields) {
92
          $form['settings'][$entity_type_id][$bundle]['translatable'] = array(
93
            '#type' => 'checkbox',
94
            '#default_value' => content_translation_enabled($entity_type_id, $bundle),
95 96
          );

97
          $field_settings = content_translation_get_config($entity_type_id, $bundle, 'fields');
98 99 100 101 102 103 104
          foreach ($fields as $field_name => $definition) {
            $translatable = !empty($field_settings[$field_name]);

            // We special case Field API fields as they always natively support
            // translation.
            // @todo Remove this special casing as soon as configurable and
            //   base field definitions are "unified".
105 106 107
            if ($definition->isConfigurable() && ($field = FieldService::fieldInfo()->getField($entity_type_id, $field_name))) {
              $instance = FieldService::fieldInfo()->getInstance($entity_type_id, $bundle, $field_name);
              $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = array(
108
                '#label' => $instance->getLabel(),
109 110 111 112 113
                '#type' => 'checkbox',
                '#default_value' => $translatable,
              );
              $column_element = content_translation_field_sync_widget($instance);
              if ($column_element) {
114
                $form['settings'][$entity_type_id][$bundle]['columns'][$field_name] = $column_element;
115 116 117

                // @todo This should not concern only files.
                if (isset($column_element['#options']['file'])) {
118
                  $dependent_options_settings["settings[{$entity_type_id}][{$bundle}][columns][{$field_name}]"] = array('file');
119
                }
120 121
              }
            }
122 123 124 125
            // Instead we need to rely on field definitions to determine whether
            // fields support translation. Whether they are actually enabled is
            // determined through our settings. As a consequence only fields
            // that support translation can be enabled or disabled.
126
            elseif (isset($field_settings[$field_name]) || $definition->isTranslatable()) {
127
              $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = array(
128
                '#label' => $definition->getLabel(),
129 130 131 132
                '#type' => 'checkbox',
                '#default_value' => $translatable,
              );
            }
133
          }
134
        }
135 136 137
      }
    }
  }
138
  $settings = array('dependent_selectors' => $dependent_options_settings);
139 140 141
  $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';
142 143
}

144 145 146
/**
 * (proxied) Implements hook_preprocess_HOOK();
 */
147
function _content_translation_preprocess_language_content_settings_table(&$variables) {
148 149
  // Alter the 'build' variable injecting the translation settings if the user
  // has the required permission.
150
  if (!user_access('administer content translation')) {
151 152 153 154 155 156 157 158 159 160 161
    return;
  }

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

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

  foreach (element_children($element) as $bundle) {
    $field_names = !empty($element[$bundle]['fields']) ? element_children($element[$bundle]['fields']) : array();
162 163 164
    if (!empty($element[$bundle]['translatable'])) {
      $checkbox_id = $element[$bundle]['translatable']['#id'];
    }
165 166
    $rows[$bundle] = $build['#rows'][$bundle];

167 168 169 170 171 172
    if (!empty($element[$bundle]['translatable'])) {
      $translatable = array(
        'data' => $element[$bundle]['translatable'],
        'class' => array('translatable'),
      );
      array_unshift($rows[$bundle]['data'], $translatable);
173

174 175 176 177 178 179 180 181
      $rows[$bundle]['data'][1]['data']['#prefix'] = '<label for="' . $checkbox_id . '">';
    }
    else {
      $translatable = array(
        'class' => array('untranslatable'),
      );
      array_unshift($rows[$bundle]['data'], $translatable);
    }
182 183 184 185 186 187 188 189 190 191 192 193 194 195

    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(
196
                '#prefix' => '<span class="visually-hidden">',
197
                '#suffix' => '</span> ',
198
                '#markup' => String::checkPlain($element[$bundle]['settings']['#label']),
199 200
              ),
              'field' => array(
201
                '#markup' => String::checkPlain($field_element['#label']),
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
              ),
            ),
            '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];
        foreach (element_children($column_element) as $key) {
          $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(
230
                    '#prefix' => '<span class="visually-hidden">',
231
                    '#suffix' => '</span> ',
232
                    '#markup' => String::checkPlain($element[$bundle]['settings']['#label']),
233 234
                  ),
                  'field' => array(
235
                    '#prefix' => '<span class="visually-hidden">',
236
                    '#suffix' => '</span> ',
237
                    '#markup' => String::checkPlain($field_element['#label']),
238 239
                  ),
                  'columns' => array(
240
                    '#markup' => String::checkPlain($column_label),
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
                  ),
                ),
                'class' => array('column'),
              ),
              array(
                'data' => '',
                'class' => array('operations'),
              ),
            ),
            'class' => array('column-settings'),
          );
        }
      }
    }
  }

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

260
/**
261
 * Form validation handler for content_translation_admin_settings_form().
262
 *
263
 * @see content_translation_admin_settings_form_submit()
264
 */
265
function content_translation_form_language_content_settings_validate(array $form, array &$form_state) {
266 267 268 269 270 271 272 273 274
  $settings = &$form_state['values']['settings'];
  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']);
275
          form_set_error($name, $form_state, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args));
276 277 278
        }

        $values = $bundle_settings['settings']['language'];
279
        if (empty($values['language_show']) && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
280
          foreach (language_list(Language::STATE_LOCKED) as $language) {
281 282
            $locked_languages[] = $language->name;
          }
283
          form_set_error($name, $form_state, t('Translation is not supported if language is always one of: @locked_languages', array('@locked_languages' => implode(', ', $locked_languages))));
284 285 286 287 288 289 290
        }
      }
    }
  }
}

/**
291
 * Form submission handler for content_translation_admin_settings_form().
292
 *
293
 * @see content_translation_admin_settings_form_validate()
294
 */
295
function content_translation_form_language_content_settings_submit(array $form, array &$form_state) {
296 297 298 299 300 301 302
  $entity_types = $form_state['values']['entity_types'];
  $settings = &$form_state['values']['settings'];

  // 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.
  foreach ($settings as $entity_type => &$entity_settings) {
303
    foreach ($entity_settings as &$bundle_settings) {
304 305 306
      if (!empty($bundle_settings['translatable'])) {
        $bundle_settings['translatable'] = $bundle_settings['translatable'] && $entity_types[$entity_type];
      }
307 308 309
      if (!empty($bundle_settings['fields'])) {
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
          $bundle_settings['fields'][$field_name] = $translatable && $bundle_settings['translatable'];
310 311 312 313 314
          // 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])) {
            $bundle_settings['fields'][$field_name] = FALSE;
          }
315 316 317 318 319
        }
      }
    }
  }

320
  _content_translation_update_field_translatability($settings);
321 322 323 324
  drupal_set_message(t('Settings successfully updated.'));
}

/**
325
 * Stores content translation settings.
326 327 328 329 330 331 332 333 334 335
 *
 * @param array $settings
 *   An associative array of settings keyed by entity type and bundle. At bundle
 *   level the following keys are available:
 *   - translatable: The bundle translatability status, which is a bool.
 *   - settings: An array of language configuration settings as defined by
 *     language_save_default_configuration().
 *   - fields: An associative array with field names as keys and a boolean as
 *     value, indicating field translatability.
 */
336
function _content_translation_update_field_translatability($settings) {
337 338 339
  // Update translatability for configurable fields.
  // @todo Remove this once configurable fields rely on entity field info to
  //   track translatability. See https://drupal.org/node/2018685.
340
  foreach ($settings as $entity_type => $entity_settings) {
341
    $fields = array();
342
    foreach ($entity_settings as $bundle_settings) {
343 344 345 346 347
      // Collapse field settings since here we have per instance settings, but
      // translatability has per-field scope. We assume that all the field
      // instances have the same value.
      if (!empty($bundle_settings['fields'])) {
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
348 349
          // If translatability changes for at least one field instance we need
          // to switch field translatability.
350
          $field = FieldService::fieldInfo()->getField($entity_type, $field_name);
351
          if ($field && $field->isTranslatable() !== $translatable) {
352
            $fields[$field_name] = $translatable;
353
          }
354 355 356
        }
      }
    }
357 358 359 360 361 362
    // Store updated fields.
    foreach ($fields as $field_name => $translatable) {
      $field = FieldService::fieldInfo()->getField($entity_type, $field_name);
      $field->translatable = $translatable;
      $field->save();
    }
363 364
  }

365
  content_translation_save_settings($settings);
366
}