You are here

class TranslatorForm in Translation Management Tool 8

Form controller for the translator edit forms.

Hierarchy

Expanded class hierarchy of TranslatorForm

Related topics

1 file declares its use of TranslatorForm
TranslatorPluginUiBase.php in src/TranslatorPluginUiBase.php

File

src/Form/TranslatorForm.php, line 18

Namespace

Drupal\tmgmt\Form
View source
class TranslatorForm extends EntityForm {

  /**
   * @var \Drupal\tmgmt\TranslatorInterface
   */
  protected $entity;

  /**
   * Translator plugin manager.
   *
   * @var \Drupal\tmgmt\TranslatorManager
   */
  protected $translatorManager;

  /**
   * Source plugin manager.
   *
   * @var \Drupal\tmgmt\SourceManager
   */
  protected $sourceManager;

  /**
   * Constructs an EntityForm object.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface
   *   The module handler service.
   * @param \Drupal\tmgmt\TranslatorManager $translator_manager
   *   The translator plugin manager.
   */
  public function __construct(TranslatorManager $translator_manager, SourceManager $source_manager) {
    $this->translatorManager = $translator_manager;
    $this->sourceManager = $source_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.tmgmt.translator'), $container
      ->get('plugin.manager.tmgmt.source'));
  }

  /**
   * Overrides Drupal\Core\Entity\EntityForm::form().
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    if ($this->operation == 'clone') {
      $this->entity = $this->entity
        ->createDuplicate();
    }
    $entity = $this->entity;

    // Check if the translator is currently in use.
    if ($busy = !$entity
      ->isNew() ? tmgmt_translator_busy($entity
      ->id()) : FALSE) {
      \Drupal::messenger()
        ->addWarning(t("This provider is currently in use. It cannot be deleted. The chosen provider Plugin cannot be changed."));
    }
    $available = $this->translatorManager
      ->getLabels();

    // If the translator plugin is not set, pick the first available plugin as the
    // default.
    if (!$entity
      ->hasPlugin()) {
      $entity
        ->setPluginID(key($available));
    }
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => t('Label'),
      '#description' => t('The label of the provider.'),
      '#default_value' => $entity
        ->label(),
      '#required' => TRUE,
      '#size' => 32,
      '#maxlength' => 64,
    );
    $form['name'] = array(
      '#type' => 'machine_name',
      '#title' => t('Machine name'),
      '#description' => t('The machine readable name of this provider. It must be unique, and it must contain only alphanumeric characters and underscores. Once created, you will not be able to change this value!'),
      '#default_value' => $entity
        ->id(),
      '#machine_name' => array(
        'exists' => '\\Drupal\\tmgmt\\Entity\\Translator::load',
        'source' => array(
          'label',
        ),
      ),
      '#disabled' => !$entity
        ->isNew(),
      '#size' => 32,
      '#maxlength' => 64,
    );
    $form['description'] = array(
      '#type' => 'textarea',
      '#title' => t('Description'),
      '#description' => t('The description of the provider.'),
      '#default_value' => $entity
        ->getDescription(),
      '#size' => 32,
      '#maxlength' => 255,
    );
    $form['auto_accept'] = array(
      '#type' => 'checkbox',
      '#title' => t('Auto accept finished translations'),
      '#description' => t('This skips the reviewing process and automatically accepts all translations as soon as they are returned by the translation provider.'),
      '#default_value' => $entity
        ->isAutoAccept(),
    );
    $form['plugin_wrapper'] = array(
      '#type' => 'container',
      '#prefix' => '<div id="tmgmt-plugin-wrapper">',
      '#suffix' => '</div>',
    );

    // Pull the translator plugin info if any.
    if ($entity
      ->hasPlugin()) {
      $definition = $this->translatorManager
        ->getDefinition($entity
        ->getPluginId());
      $form['plugin_wrapper']['plugin'] = array(
        '#type' => 'select',
        '#title' => t('Provider plugin'),
        '#submit' => array(
          '::updateRemoteLanguagesMappings',
        ),
        '#limit_validation_errors' => array(
          array(
            'plugin',
          ),
        ),
        '#executes_submit_callback' => TRUE,
        '#description' => isset($definition['description']) ? Xss::filter($definition['description']) : '',
        '#options' => $available,
        '#default_value' => $entity
          ->getPluginId(),
        '#required' => TRUE,
        '#disabled' => $busy,
        '#ajax' => array(
          'callback' => array(
            $this,
            'ajaxTranslatorPluginSelect',
          ),
          'wrapper' => 'tmgmt-plugin-wrapper',
        ),
      );

      // Add the provider logo in the settings wrapper.
      if (isset($definition['logo'])) {
        $form['plugin_wrapper']['logo'] = $logo_render_array = [
          '#theme' => 'image',
          '#uri' => file_create_url(drupal_get_path('module', $definition['provider']) . '/' . $definition['logo']),
          '#alt' => $definition['label'],
          '#title' => $definition['label'],
          '#attributes' => [
            'class' => 'tmgmt-logo-settings',
          ],
          '#suffix' => '<div class="clearfix"></div>',
        ];
      }
      $form['plugin_wrapper']['settings'] = array(
        '#type' => 'details',
        '#title' => t('@plugin plugin settings', array(
          '@plugin' => $definition['label'],
        )),
        '#tree' => TRUE,
        '#open' => TRUE,
      );

      // Add the translator plugin settings form.
      $plugin_ui = $this->translatorManager
        ->createUIInstance($entity
        ->getPluginId());
      $form_state
        ->set('busy', $busy);
      $form['plugin_wrapper']['settings'] += $plugin_ui
        ->buildConfigurationForm($form['plugin_wrapper']['settings'], $form_state);
      if (!Element::children($form['plugin_wrapper']['settings'])) {
        $form['#description'] = t("The @plugin plugin doesn't provide any settings.", array(
          '@plugin' => $plugin_ui
            ->getPluginDefinition()['label'],
        ));
      }

      // If current translator is configured to provide remote language mapping
      // provide the form to configure mappings, unless it does not exists yet.
      if ($entity
        ->providesRemoteLanguageMappings()) {
        $form['plugin_wrapper']['remote_languages_mappings'] = array(
          '#tree' => TRUE,
          '#type' => 'details',
          '#title' => t('Remote languages mappings'),
          '#description' => t('Here you can specify mappings of your local language codes to the translator language codes.'),
          '#open' => TRUE,
        );
        $options = $entity
          ->getSupportedRemoteLanguages();
        foreach ($entity
          ->getRemoteLanguagesMappings() as $local_language => $remote_language) {
          $form['plugin_wrapper']['remote_languages_mappings'][$local_language] = array(
            '#type' => 'textfield',
            '#title' => \Drupal::languageManager()
              ->getLanguage($local_language)
              ->getName() . ' (' . $local_language . ')',
            '#default_value' => $remote_language,
            '#size' => 6,
          );
          if (!empty($options)) {
            $form['plugin_wrapper']['remote_languages_mappings'][$local_language]['#type'] = 'select';
            $form['plugin_wrapper']['remote_languages_mappings'][$local_language]['#options'] = $options;
            $form['plugin_wrapper']['remote_languages_mappings'][$local_language]['#empty_option'] = ' - ';
            unset($form['plugin_wrapper']['remote_languages_mappings'][$local_language]['#size']);
          }
        }
      }
    }
    $form['#attached']['library'][] = 'tmgmt/admin';
    return $form;
  }

  /**
   * Updates remote languages mappings.
   *
   * @param array $form
   *   An associative array containing the initial structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the complete form.
   */
  public static function updateRemoteLanguagesMappings(array $form, FormStateInterface $form_state) {
    if (!empty($form_state
      ->getUserInput()['remote_languages_mappings'])) {

      // The user input containing remote languages mappings from an old
      // translator, so We have to remove them from here.
      $user_input = $form_state
        ->getUserInput();
      unset($user_input['remote_languages_mappings']);
      $form_state
        ->setUserInput($user_input);
    }
    $form_state
      ->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    if (!$form_state
      ->getValue('plugin')) {
      $form_state
        ->setErrorByName('plugin', $this
        ->t('You have to select a translator plugin.'));
    }
    $plugin_ui = $this->translatorManager
      ->createUIInstance($this->entity
      ->getPluginID());
    $plugin_ui
      ->validateConfigurationForm($form, $form_state);
  }

  /**
   * Overrides Drupal\Core\Entity\EntityForm::save().
   */
  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
    $status = $entity
      ->save();
    if ($status === SAVED_UPDATED) {
      \Drupal::messenger()
        ->addStatus($this
        ->t('%label configuration has been updated.', array(
        '%label' => $entity
          ->label(),
      )));
    }
    else {
      \Drupal::messenger()
        ->addStatus($this
        ->t('%label configuration has been created.', array(
        '%label' => $entity
          ->label(),
      )));
    }
    $form_state
      ->setRedirect('entity.tmgmt_translator.collection');
  }

  /**
   * {@inheritdoc}
   */
  public function delete(array $form, FormStateInterface $form_state) {
    $form_state
      ->setRedirectUrl($this->entity
      ->toUrl('delete-form'));
  }

  /**
   * Ajax callback for loading the translator plugin settings form for the
   * currently selected translator plugin.
   */
  public static function ajaxTranslatorPluginSelect(array $form, FormStateInterface $form_state) {
    return $form['plugin_wrapper'];
  }

}

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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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.
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.
TranslatorForm::$entity protected property Overrides EntityForm::$entity
TranslatorForm::$sourceManager protected property Source plugin manager.
TranslatorForm::$translatorManager protected property Translator plugin manager.
TranslatorForm::ajaxTranslatorPluginSelect public static function Ajax callback for loading the translator plugin settings form for the currently selected translator plugin.
TranslatorForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TranslatorForm::delete public function
TranslatorForm::form public function Overrides Drupal\Core\Entity\EntityForm::form(). Overrides EntityForm::form
TranslatorForm::save public function Overrides Drupal\Core\Entity\EntityForm::save(). Overrides EntityForm::save
TranslatorForm::updateRemoteLanguagesMappings public static function Updates remote languages mappings.
TranslatorForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
TranslatorForm::__construct public function Constructs an EntityForm object.
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.