You are here

class MergeTermsTarget in Term Merge 8

Term merge target terms form.

Hierarchy

Expanded class hierarchy of MergeTermsTarget

1 file declares its use of MergeTermsTarget
MergeTermsTargetTest.php in tests/src/Kernel/Form/MergeTermsTargetTest.php
1 string reference to 'MergeTermsTarget'
term_merge.routing.yml in ./term_merge.routing.yml
term_merge.routing.yml

File

src/Form/MergeTermsTarget.php, line 15

Namespace

Drupal\term_merge\Form
View source
class MergeTermsTarget extends FormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The term storage handler.
   *
   * @var \Drupal\taxonomy\TermStorageInterface
   */
  protected $termStorage;

  /**
   * The private temporary storage factory.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  private $tempStoreFactory;

  /**
   * The vocabulary.
   *
   * @var \Drupal\taxonomy\VocabularyInterface
   */
  private $vocabulary;

  /**
   * Constructs an OverviewTerms object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity manager service.
   * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $tempStoreFactory
   *   The private temporary storage factory.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, PrivateTempStoreFactory $tempStoreFactory) {
    $this->entityTypeManager = $entityTypeManager;
    $this->termStorage = $entityTypeManager
      ->getStorage('taxonomy_term');
    $this->tempStoreFactory = $tempStoreFactory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('tempstore.private'));
  }

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'taxonomy_merge_terms_target';
  }

  /**
   * Callback for the form title.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   *   The title.
   *
   * @SuppressWarnings(camelCase)
   */
  public function titleCallback() {
    return $this
      ->t('Please select a target term');
  }

  /**
   * {@inheritdoc}
   *
   * @SuppressWarnings(camelCase)
   */
  public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL) {
    $this->vocabulary = $taxonomy_vocabulary;
    $form['description']['#markup'] = $this
      ->t('Please enter a new term or select an existing term to merge into.');
    $form['new'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('New term'),
    ];
    $form['existing'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Existing term'),
      '#empty_option' => $this
        ->t('Select an existing term'),
      '#options' => $this
        ->buildExistingTermsOptions(),
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#button_type' => 'primary',
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * @SuppressWarnings(camelCase)
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $new = !empty($form_state
      ->getValue('new'));
    $existing = !empty($form_state
      ->getValue('existing'));
    if ($new !== $existing) {
      return;
    }
    $form_state
      ->setErrorByName('new', $this
      ->t('You must either select an existing term or enter a new term.'));
  }

  /**
   * {@inheritdoc}
   *
   * @SuppressWarnings(camelCase)
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if (!empty($form_state
      ->getValue('new'))) {
      $this
        ->getTempStore()
        ->set('target', $form_state
        ->getValue('new'));
    }
    if (!empty($form_state
      ->getValue('existing'))) {
      $term = $this->termStorage
        ->load($form_state
        ->getValue('existing'));
      $this
        ->getTempStore()
        ->set('target', $term);
    }
    $routeName = 'entity.taxonomy_vocabulary.merge_confirm';
    $routeParameters['taxonomy_vocabulary'] = $this->vocabulary
      ->id();
    $form_state
      ->setRedirect($routeName, $routeParameters);
  }

  /**
   * Builds an array of existing terms.
   *
   * @return string[]
   *   Existing term labels keyed by id.
   */
  private function buildExistingTermsOptions() {
    $query = $this->termStorage
      ->getQuery();
    $query
      ->condition('vid', $this->vocabulary
      ->id())
      ->condition('tid', $this
      ->getSelectedTermIds(), 'NOT IN');
    $terms = $this->termStorage
      ->loadMultiple($query
      ->execute());
    $options = [];
    foreach ($terms as $term) {
      $options[$term
        ->id()] = $term
        ->label();
    }
    return $options;
  }

  /**
   * Retrieves the selected term ids from the temp store.
   *
   * @return array
   *   The selected term ids.
   */
  private function getSelectedTermIds() {
    return (array) $this
      ->getTempStore()
      ->get('terms');
  }

  /**
   * Retrieves the term_merge private temp store.
   *
   * @return \Drupal\Core\TempStore\PrivateTempStore
   *   The private temp store.
   */
  private function getTempStore() {
    return $this->tempStoreFactory
      ->get('term_merge');
  }

}

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.
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.
MergeTermsTarget::$entityTypeManager protected property The entity type manager.
MergeTermsTarget::$tempStoreFactory private property The private temporary storage factory.
MergeTermsTarget::$termStorage protected property The term storage handler.
MergeTermsTarget::$vocabulary private property The vocabulary.
MergeTermsTarget::buildExistingTermsOptions private function Builds an array of existing terms.
MergeTermsTarget::buildForm public function Plugin annotation @SuppressWarnings(camelCase); Overrides FormInterface::buildForm
MergeTermsTarget::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MergeTermsTarget::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MergeTermsTarget::getSelectedTermIds private function Retrieves the selected term ids from the temp store.
MergeTermsTarget::getTempStore private function Retrieves the term_merge private temp store.
MergeTermsTarget::submitForm public function Plugin annotation @SuppressWarnings(camelCase); Overrides FormInterface::submitForm
MergeTermsTarget::titleCallback public function Callback for the form title.
MergeTermsTarget::validateForm public function Plugin annotation @SuppressWarnings(camelCase); Overrides FormBase::validateForm
MergeTermsTarget::__construct public function Constructs an OverviewTerms object.
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.
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.