You are here

class TranslateBlockForm in Layout Builder Symmetric Translations 8

Provides a form to translate a block plugin in the Layout Builder.

@internal Form classes are internal.

Hierarchy

Expanded class hierarchy of TranslateBlockForm

1 string reference to 'TranslateBlockForm'
layout_builder_st.routing.yml in ./layout_builder_st.routing.yml
layout_builder_st.routing.yml

File

src/Form/TranslateBlockForm.php, line 26

Namespace

Drupal\layout_builder_st\Form
View source
class TranslateBlockForm extends FormBase {
  use AjaxFormHelperTrait;
  use LayoutRebuildTrait;

  /**
   * The section storage.
   *
   * @var \Drupal\layout_builder_st\TranslatableSectionStorageInterface
   */
  protected $sectionStorage;

  /**
   * The UUID of the component.
   *
   * @var string
   */
  protected $uuid;

  /**
   * The layout tempstore repository.
   *
   * @var \Drupal\layout_builder\LayoutTempstoreRepositoryInterface
   */
  protected $layoutTempstoreRepository;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * @var \Drupal\Core\Config\TypedConfigManagerInterface
   */
  protected $typedConfigManager;

  /**
   * Constructs a new TranslateBlockForm.
   */
  public function __construct(LayoutTempstoreRepositoryInterface $layout_tempstore_repository, ModuleHandlerInterface $module_handler, TypedConfigManagerInterface $typed_config_manager) {
    $this->layoutTempstoreRepository = $layout_tempstore_repository;
    $this->moduleHandler = $module_handler;
    $this->typedConfigManager = $typed_config_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('layout_builder.tempstore_repository'), $container
      ->get('module_handler'), $container
      ->get('config.typed'));
  }

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

  /**
   * Builds the block translation form.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param \Drupal\layout_builder\SectionStorageInterface $section_storage
   *   The section storage being configured.
   * @param int $delta
   *   The delta of the section.
   * @param string $region
   *   The region of the block.
   * @param string $uuid
   *   The UUID of the block being updated.
   *
   * @return array
   *   The form array.
   */
  public function buildForm(array $form, FormStateInterface $form_state, TranslatableSectionStorageInterface $section_storage = NULL, $delta = NULL, $region = NULL, $uuid = NULL) {
    $component = $section_storage
      ->getSection($delta)
      ->getComponent($uuid);
    $this->sectionStorage = $section_storage;
    $this->uuid = $component
      ->getUuid();
    $configuration = $component
      ->getPlugin()
      ->getConfiguration();
    $type_definition = $this->typedConfigManager
      ->getDefinition('block.settings.' . $component
      ->getPlugin()
      ->getPluginId());

    /** @var \Drupal\Core\TypedData\DataDefinitionInterface $definition */
    $definition = new $type_definition['definition_class']($type_definition);
    $definition
      ->setClass($type_definition['class']);

    /** @var \Drupal\Core\Config\Schema\Mapping $typed_data */
    $typed_data = $type_definition['class']::createInstance($definition);
    $typed_data
      ->setValue($configuration);
    $translated_config = $this->sectionStorage
      ->getTranslatedComponentConfiguration($this->uuid);
    foreach (array_keys($configuration) as $key) {
      if (!isset($translated_config[$key])) {
        $translated_config[$key] = NULL;
      }
    }
    $form['translation'] = $this
      ->createTranslationElement($section_storage
      ->getSourceLanguage(), $section_storage
      ->getTranslationLanguage(), $typed_data, $translated_config);
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Translate'),
    ];
    if ($this
      ->isAjax()) {
      $form['submit']['#ajax']['callback'] = '::ajaxSubmit';

      // @todo static::ajaxSubmit() requires data-drupal-selector to be the same
      //   between the various Ajax requests. A bug in
      //   \Drupal\Core\Form\FormBuilder prevents that from happening unless
      //   $form['#id'] is also the same. Normally, #id is set to a unique HTML
      //   ID via Html::getUniqueId(), but here we bypass that in order to work
      //   around the data-drupal-selector bug. This is okay so long as we
      //   assume that this form only ever occurs once on a page. Remove this
      //   workaround in https://www.drupal.org/node/2897377.
      $form['#id'] = Html::getId($form_state
        ->getBuildInfo()['form_id']);
    }
    return $form;
  }

  /**
   * Creates translation element.
   *
   * @param \Drupal\Core\Language\LanguageInterface $source_language
   *   The source language.
   * @param \Drupal\Core\Language\LanguageInterface $translation_language
   *   The translation language.
   * @param \Drupal\Core\TypedData\TraversableTypedDataInterface $typed_data
   *   The typed data of the configuration settings.
   * @param array $translated_configuration
   *   The translated configuration.
   *
   * @return array
   *   The translation element render array.
   */
  protected function createTranslationElement(LanguageInterface $source_language, LanguageInterface $translation_language, TraversableTypedDataInterface $typed_data, array $translated_configuration) {
    if ($this->moduleHandler
      ->moduleExists('config_translation')) {

      // If config_translation is installed let it handle creating complex
      // schema.
      $form_element = ConfigTranslationFormBase::createFormElement($typed_data);
      $element_build = $form_element
        ->getTranslationBuild($source_language, $translation_language, $typed_data
        ->getValue(), $translated_configuration, []);
    }
    else {

      // If config_translation is not enabled only provide the 'label'
      // translation.
      if (($label_data = $typed_data
        ->get('label')) && $label_data instanceof StringData) {
        $element_build['label']['source'] = [
          '#type' => 'item',
          '#title' => $this
            ->t('Label'),
          '#markup' => $label_data
            ->getValue() ?: '(' . $this
            ->t('Empty') . ')',
          '#parents' => [
            'source',
            'label',
          ],
        ];
        $element_build['label']['translation'] = [
          '#type' => 'textfield',
          '#title' => $this
            ->t('Label'),
          '#default_value' => isset($translated_configuration['label']) ? $translated_configuration['label'] : '',
          '#parents' => [
            'translation',
            'label',
          ],
        ];
      }
    }
    $element_build['#tree'] = TRUE;
    return $element_build;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $section_storage = $this->sectionStorage;
    $section_storage
      ->setTranslatedComponentConfiguration($this->uuid, $form_state
      ->getValue('translation'));
    $this->layoutTempstoreRepository
      ->set($this->sectionStorage);
    $form_state
      ->setRedirectUrl($this->sectionStorage
      ->getLayoutBuilderUrl());
  }

  /**
   * {@inheritdoc}
   */
  protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state) {
    return $this
      ->rebuildAndClose($this->sectionStorage);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxFormHelperTrait::ajaxSubmit public function Submit form dialog #ajax callback.
AjaxHelperTrait::getRequestWrapperFormat protected function Gets the wrapper format of the current request.
AjaxHelperTrait::isAjax protected function Determines if the current request is via AJAX.
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
LayoutRebuildTrait::rebuildAndClose protected function Rebuilds the layout.
LayoutRebuildTrait::rebuildLayout protected function Rebuilds the layout.
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.
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.
TranslateBlockForm::$layoutTempstoreRepository protected property The layout tempstore repository.
TranslateBlockForm::$moduleHandler protected property The module handler.
TranslateBlockForm::$sectionStorage protected property The section storage.
TranslateBlockForm::$typedConfigManager protected property
TranslateBlockForm::$uuid protected property The UUID of the component.
TranslateBlockForm::buildForm public function Builds the block translation form. Overrides FormInterface::buildForm
TranslateBlockForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TranslateBlockForm::createTranslationElement protected function Creates translation element.
TranslateBlockForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
TranslateBlockForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
TranslateBlockForm::successfulAjaxSubmit protected function Allows the form to respond to a successful AJAX submission. Overrides AjaxFormHelperTrait::successfulAjaxSubmit
TranslateBlockForm::__construct public function Constructs a new TranslateBlockForm.
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.