You are here

class MetatagViewsTranslationForm in Metatag 8

Defines a form for translating meta tags for views.

@package Drupal\metatag_views\Form

Hierarchy

Expanded class hierarchy of MetatagViewsTranslationForm

File

metatag_views/src/Form/MetatagViewsTranslationForm.php, line 21

Namespace

Drupal\metatag_views\Form
View source
class MetatagViewsTranslationForm extends FormBase {
  use MetatagViewsValuesCleanerTrait;
  use StringTranslationTrait;

  /**
   * Drupal\metatag\MetatagManager definition.
   *
   * @var \Drupal\metatag\MetatagManager
   */
  protected $metatagManager;

  /**
   * The language manager.
   *
   * @var \Drupal\language\ConfigurableLanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The Views manager.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $viewsManager;

  /**
   * The Metatag token service.
   *
   * @var \Drupal\metatag\MetatagToken
   */
  protected $tokenService;

  /**
   * The Metatag tag plugin manager.
   *
   * @var \Drupal\metatag\MetatagTagPluginManager
   */
  protected $tagPluginManager;

  /**
   * The View entity object.
   *
   * @var \Drupal\views\ViewEntityInterface
   */
  protected $view;

  /**
   * View ID.
   *
   * @var string
   */
  protected $viewId;

  /**
   * View display ID.
   *
   * @var string
   */
  protected $displayId = 'default';

  /**
   * The language of the translation.
   *
   * @var \Drupal\Core\Language\LanguageInterface
   */
  protected $language;

  /**
   * The language of the translation source.
   *
   * @var \Drupal\Core\Language\LanguageInterface
   */
  protected $sourceLanguage;

  /**
   * An array of base language data.
   *
   * @var array
   */
  protected $baseData = [];

  /**
   * {@inheritdoc}
   */
  public function __construct(MetatagManagerInterface $metatag_manager, EntityTypeManagerInterface $entity_type_manager, MetatagToken $token, MetatagTagPluginManager $tagPluginManager, ConfigurableLanguageManagerInterface $language_manager) {
    $this->metatagManager = $metatag_manager;
    $this->viewsManager = $entity_type_manager
      ->getStorage('view');
    $this->tokenService = $token;
    $this->tagPluginManager = $tagPluginManager;
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('metatag.manager'), $container
      ->get('entity_type.manager'), $container
      ->get('metatag.token'), $container
      ->get('plugin.manager.metatag.tag'), $container
      ->get('language_manager'));
  }

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

  /**
   * Gets the translated values while storing a copy of the original values.
   */
  protected function prepareValues() {
    $config_name = $this->view
      ->getConfigDependencyName();
    $config_path = 'display.' . $this->displayId . '.display_options.display_extenders.metatag_display_extender.metatags';
    $configuration = $this
      ->configFactory()
      ->get($config_name);
    $this->baseData = $configuration
      ->getOriginal($config_path, FALSE);

    // Set the translation target language on the configuration factory.
    $original_language = $this->languageManager
      ->getConfigOverrideLanguage();
    $this->languageManager
      ->setConfigOverrideLanguage($this->language);

    // Read in translated values.
    $configuration = $this
      ->configFactory()
      ->get($config_name);
    $translated_values = $configuration
      ->get($config_path);

    // Set the configuration language back.
    $this->languageManager
      ->setConfigOverrideLanguage($original_language);
    return $translated_values;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Get the parameters from request.
    $this->viewId = $this
      ->getRequest()
      ->get('view_id');
    $this->displayId = $this
      ->getRequest()
      ->get('display_id');
    $langcode = $this
      ->getRequest()
      ->get('langcode');
    $this->view = $this->viewsManager
      ->load($this->viewId);
    $this->language = $this->languageManager
      ->getLanguage($langcode);
    $this->sourceLanguage = $this->view
      ->language();

    // Get meta tags from the view entity.
    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'config_translation/drupal.config_translation.admin';
    $form['#title'] = $this
      ->t('Edit @language translation for %view: %display metatags', [
      '%view' => $this->view
        ->label(),
      '%display' => $this->view
        ->getDisplay($this->displayId)['display_title'],
      '@language' => $this->language
        ->getName(),
    ]);
    $form['metatags'] = $this
      ->form($form, $this
      ->prepareValues());
    $form['metatags']['#title'] = $this
      ->t('Metatags');
    $form['metatags']['#type'] = 'fieldset';
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * Add the translation form element for meta tags available in the source.
   */
  public function form(array $element, array $translated_values) {
    $translated_values = $this
      ->clearMetatagViewsDisallowedValues($translated_values);

    // Only offer form elements for tags present in the source language.
    $source_values = $this
      ->removeEmptyTags($this->baseData);

    // Add the outer fieldset.
    $element += [
      '#type' => 'details',
    ];
    $element += $this->tokenService
      ->tokenBrowser([
      'view',
    ]);
    foreach ($source_values as $tag_id => $value) {
      $tag = $this->tagPluginManager
        ->createInstance($tag_id);
      $tag
        ->setValue($translated_values[$tag_id]);
      $form_element = $tag
        ->form($element);
      $element[$tag_id] = [
        '#theme' => 'config_translation_manage_form_element',
        'source' => [
          '#type' => 'item',
          '#title' => $form_element['#title'],
          '#markup' => $value,
        ],
        'translation' => $form_element,
      ];
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Get the values of metatags.
    $values = $form_state
      ->getValue('metatags');
    $translated_values = array_combine(array_keys($values), array_column($values, 'translation'));
    $config_name = $this->view
      ->getConfigDependencyName();
    $config_path = 'display.' . $this->displayId . '.display_options.display_extenders.metatag_display_extender.metatags';

    // Set configuration values based on form submission and source values.
    $base_config = $this
      ->configFactory()
      ->getEditable($config_name);
    $config_translation = $this->languageManager
      ->getLanguageConfigOverride($this->language
      ->getId(), $config_name);

    // Save the configuration values, if they are different from the source
    // values in the base configuration. Otherwise remove the override.
    $source_values = $this
      ->removeEmptyTags($base_config
      ->get($config_path));
    if ($source_values !== $translated_values) {
      $config_translation
        ->set($config_path, $translated_values);
    }
    else {
      $config_translation
        ->clear($config_path);
    }

    // If no overrides, delete language specific configuration file.
    $saved_config = $config_translation
      ->get();
    if (empty($saved_config)) {
      $config_translation
        ->delete();
    }
    else {
      $config_translation
        ->save();
    }

    // Redirect back to the views list.
    $form_state
      ->setRedirect('metatag_views.metatags.translate_overview', [
      'view_id' => $this->viewId,
      'display_id' => $this->displayId,
    ]);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Successfully updated @language translation.', [
      '@language' => $this->language
        ->getName(),
    ]));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
MetatagViewsTranslationForm::$baseData protected property An array of base language data.
MetatagViewsTranslationForm::$displayId protected property View display ID.
MetatagViewsTranslationForm::$language protected property The language of the translation.
MetatagViewsTranslationForm::$languageManager protected property The language manager.
MetatagViewsTranslationForm::$metatagManager protected property Drupal\metatag\MetatagManager definition.
MetatagViewsTranslationForm::$sourceLanguage protected property The language of the translation source.
MetatagViewsTranslationForm::$tagPluginManager protected property The Metatag tag plugin manager.
MetatagViewsTranslationForm::$tokenService protected property The Metatag token service.
MetatagViewsTranslationForm::$view protected property The View entity object.
MetatagViewsTranslationForm::$viewId protected property View ID.
MetatagViewsTranslationForm::$viewsManager protected property The Views manager.
MetatagViewsTranslationForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MetatagViewsTranslationForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MetatagViewsTranslationForm::form public function Add the translation form element for meta tags available in the source.
MetatagViewsTranslationForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MetatagViewsTranslationForm::prepareValues protected function Gets the translated values while storing a copy of the original values.
MetatagViewsTranslationForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MetatagViewsTranslationForm::__construct public function
MetatagViewsValuesCleanerTrait::clearMetatagViewsDisallowedValues public function Clears the metatag form state values from illegal elements.
MetatagViewsValuesCleanerTrait::removeEmptyTags public function Removes tags that are empty.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.