content_translation.admin.inc 13.7 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\ContentEntityTypeInterface;
10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Language\LanguageInterface;
12
use Drupal\Core\Render\Element;
13
use Drupal\field\FieldInstanceConfigInterface;
14

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

27 28
  $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($field->getType());
  $column_groups = $definition['column_groups'];
29
  if (!empty($column_groups) && count($column_groups) > 1) {
30 31 32
    $options = array();
    $default = array();

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

38 39
    $settings = array('dependent_selectors' => array('instance[settings][translation_sync]' => array('file')));

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

  return $element;
}

/**
 * (proxied) Implements hook_form_FORM_ID_alter().
62
 */
63
function _content_translation_form_language_content_settings_form_alter(array &$form, array &$form_state) {
64 65
  // Inject into the content language settings the translation settings if the
  // user has the required permission.
66
  if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
67 68 69 70
    return;
  }

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

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

79
  $dependent_options_settings = array();
80
  $entity_manager = Drupal::entityManager();
81
  foreach ($form['#labels'] as $entity_type_id => $label) {
82 83 84
    $entity_type = $entity_manager->getDefinition($entity_type_id);
    $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $entity_manager->getFieldStorageDefinitions($entity_type_id) : array();

85
    foreach (entity_get_bundles($entity_type_id) as $bundle => $bundle_info) {
86 87 88
      // 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.
89
      $form['settings'][$entity_type_id][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE;
90

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

101
          $field_settings = content_translation_get_config($entity_type_id, $bundle, 'fields');
102
          foreach ($fields as $field_name => $definition) {
103 104
            // Allow to configure only fields supporting multilingual storage.
            if (!empty($storage_definitions[$field_name]) && $storage_definitions[$field_name]->isTranslatable()) {
105
              $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = array(
106
                '#label' => $definition->getLabel(),
107
                '#type' => 'checkbox',
108
                '#default_value' => $definition->isTranslatable(),
109
              );
110 111 112 113 114 115 116 117 118 119 120
              // Display the column translatability configuration widget.
              // @todo Remove this special casing when arbitrary settings can be
              //   stored for any field. See https://drupal.org/node/2224761.
              if ($definition instanceof FieldInstanceConfigInterface) {
                $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');
                  }
121
                }
122 123
              }
            }
124
          }
125
        }
126 127 128
      }
    }
  }
129

130
  $settings = array('dependent_selectors' => $dependent_options_settings);
131 132 133
  $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';
134 135
}

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

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

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

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

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

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

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

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

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

        $values = $bundle_settings['settings']['language'];
271
        if (empty($values['language_show']) && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
272
          foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $language) {
273 274
            $locked_languages[] = $language->name;
          }
275
          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))));
276 277 278 279 280 281 282
        }
      }
    }
  }
}

/**
283
 * Form submission handler for content_translation_admin_settings_form().
284
 *
285
 * @see content_translation_admin_settings_form_validate()
286
 */
287
function content_translation_form_language_content_settings_submit(array $form, array &$form_state) {
288 289 290 291 292 293
  $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.
294 295
  foreach ($settings as $entity_type_id => &$entity_settings) {
    foreach ($entity_settings as $bundle => &$bundle_settings) {
296
      if (!empty($bundle_settings['translatable'])) {
297
        $bundle_settings['translatable'] = $bundle_settings['translatable'] && $entity_types[$entity_type_id];
298
      }
299
      if (!empty($bundle_settings['fields'])) {
300
        $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle);
301
        foreach ($bundle_settings['fields'] as $field_name => $translatable) {
302
          $translatable = $translatable && $bundle_settings['translatable'];
303 304 305
          // 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])) {
306
            $translatable = FALSE;
307
          }
308 309 310 311 312 313 314 315 316 317 318 319 320 321
          // If we have a storable field definition we directly persist any
          // change to translatability, otherwise we store changes in our config
          // so we can properly alter field definitions later.
          // @todo Remove this special casing when any field definition can have
          //   a configurable bundle override. See
          //   https://drupal.org/node/2224761.
          $definition = $definitions[$field_name];
          if ($definition instanceof FieldInstanceConfigInterface) {
            if ($definition->isTranslatable() != $translatable) {
              $definition->setTranslatable($translatable);
              $definition->save();
            }
            // Do not save configurable fields unnecessarily.
            unset($bundle_settings['fields'][$field_name]);
322
          }
323 324 325 326 327
        }
      }
    }
  }

328
  content_translation_save_settings($settings);
329
  drupal_set_message(t('Settings successfully updated.'));
330
}