locale_override-8.x-1.1/src/Form/LocaleOverrideImportForm.php

src/Form/LocaleOverrideImportForm.php
<?php

namespace Drupal\locale_override\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Locale Override configuration import form.
 */
class LocaleOverrideImportForm extends ConfigFormBase {

  /**
   * The cache tags invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
   */
  protected $cacheTagsInvalidator;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->cacheTagsInvalidator = $container->get('cache_tags.invalidator');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'locale_override_import_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['locale_override.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['strings'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Translated strings'),
      '#description' => $this->t('Enter one translatable string per line. Optional context should be delimited using a pipe (|) character. (i.e Some string|context)'),
      '#required' => TRUE,
    ];

    $form = parent::buildForm($form, $form_state);
    $form['actions']['submit']['#value'] = $this->t('Import strings');
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $strings = $this->config('locale_override.settings')
      ->get('strings');
    $values = preg_split('/\r\n|\r|\n/', trim($form_state->getValue('strings')));
    foreach ($values as $value) {
      if (strpos($value, '|') !== FALSE) {
        list($source, $context) = explode('|', $value);
      }
      else {
        $source = $value;
        $context = '';
      }
      $strings[md5($source . $context)] = [
        'source' => $source,
        'translation' => $source,
        'context' => $context,
        'javascript' => FALSE,
      ];
    }

    // Save config.
    $this->config('locale_override.settings')
      ->set('strings', $strings)
      ->save();

    // Clear cache.
    $this->cacheTagsInvalidator->invalidateTags(['local_override']);

    // Display message.
    $this->messenger()->addStatus($this->t('The strings have been imported.'));

    // Redirect to the settings form.
    $form_state->setRedirectUrl(Url::fromRoute('locale_override.settings'));
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc