You are here

public function StringoverridesAdminForm::submitForm in String Overrides 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

src/Form/StringoverridesAdminForm.php, line 225

Class

StringoverridesAdminForm
Class StringoverridesAdminForm.

Namespace

Drupal\stringoverrides\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $language = $form_state
    ->getValue('lang');

  // Format the words correctly for easy use then translating.
  $words = [
    TRUE => [],
    FALSE => [],
  ];

  // Drupal config key can't have some characters, we need index for each
  // contexts string and array to keep track .
  $config_enabled = \Drupal::service('config.factory')
    ->getEditable('stringoverrides.string_override.' . $language);
  $config_disabled = \Drupal::service('config.factory')
    ->getEditable('stringoverrides.string_override.' . $language . '_disabled');
  $form_data = $form_state
    ->getValue('translations_table');
  foreach ($form_data as $i => $string) {
    if (!empty($string['source'])) {
      $context = $string['context'];
      list($source, $translation) = str_replace("\r", '', [
        $string['source'],
        $string['translation'],
      ]);
      $words[$string['enabled']][$context]['context'] = $context;
      $words[$string['enabled']][$context]['translations'][] = [
        'source' => $source,
        'translation' => $translation,
      ];
    }
  }
  ksort($words[TRUE]);
  ksort($words[FALSE]);

  // Convert string array key to numeric array key, because Drupal config
  // doesn't support some characters in config keys, and sort by context.
  $words[TRUE] = array_values($words[TRUE]);
  $words[FALSE] = array_values($words[FALSE]);
  $config_enabled
    ->set('contexts', $words[TRUE]);
  $config_enabled
    ->save();
  switch ($form_state
    ->getTriggeringElement()['#id']) {
    case 'edit-submit':
      $config_disabled
        ->set('contexts', $words[FALSE]);
      $config_disabled
        ->save();
      drupal_set_message(t('Your changes have been saved.'));
      break;
    case 'edit-remove':
      $config_disabled
        ->delete();
      drupal_set_message(t('The disabled strings have been removed.'));
      break;
  }

  // Delete cache for active translation of this language.
  \Drupal::cache()
    ->delete('stringoverides:translation_for_' . $language);
}