You are here

class TaxonomyManagerForm in Taxonomy Manager 8

Same name and namespace in other branches
  1. 2.0.x src/Form/TaxonomyManagerForm.php \Drupal\taxonomy_manager\Form\TaxonomyManagerForm

Taxonomy manager class.

Hierarchy

Expanded class hierarchy of TaxonomyManagerForm

1 string reference to 'TaxonomyManagerForm'
taxonomy_manager.routing.yml in ./taxonomy_manager.routing.yml
taxonomy_manager.routing.yml

File

src/Form/TaxonomyManagerForm.php, line 28

Namespace

Drupal\taxonomy_manager\Form
View source
class TaxonomyManagerForm extends FormBase {

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

  /**
   * The link generator.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $linkGenerator;

  /**
   * The url generator.
   *
   * @var \Drupal\Core\Routing\UrlGeneratorInterface
   */
  protected $urlGenerator;

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

  /**
   * The form builder service.
   *
   * @var \Drupal\Core\Form\FormBuilder
   */
  protected $formBuilder;

  /**
   * The entity form builder.
   *
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * Constructs a \Drupal\taxonomy_manager\Form\TaxonomyManagerForm object.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The link generator service.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The url generator.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Form\FormBuilder $form_builder
   *   The form builder.
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   *   The entity form builder.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
   *   The current path.
   */
  public function __construct(ModuleHandlerInterface $module_handler, LinkGeneratorInterface $link_generator, UrlGeneratorInterface $url_generator, EntityTypeManagerInterface $entity_type_manager, FormBuilder $form_builder, EntityFormBuilderInterface $entity_form_builder, ConfigFactoryInterface $config_factory, CurrentPathStack $current_path) {
    $this->moduleHandler = $module_handler;
    $this->linkGenerator = $link_generator;
    $this->urlGenerator = $url_generator;
    $this->entityTypeManager = $entity_type_manager;
    $this->formBuilder = $form_builder;
    $this->entityFormBuilder = $entity_form_builder;
    $this->configFactory = $config_factory;
    $this->currentPath = $current_path;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('module_handler'), $container
      ->get('link_generator'), $container
      ->get('url_generator'), $container
      ->get('entity_type.manager'), $container
      ->get('form_builder'), $container
      ->get('entity.form_builder'), $container
      ->get('config.factory'), $container
      ->get('path.current'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'taxonomy_manager.vocabulary_terms_form';
  }

  /**
   * Returns the title for the whole page.
   *
   * @param string $taxonomy_vocabulary
   *   The name of the vocabulary.
   *
   * @return string
   *   The title, itself
   */
  public function getTitle($taxonomy_vocabulary) {
    return $this
      ->t("Taxonomy Manager - %voc_name", [
      "%voc_name" => $taxonomy_vocabulary
        ->label(),
    ]);
  }

  /**
   * Form constructor.
   *
   * Display a tree of all the terms in a vocabulary, with options to edit
   * each one. The form implements the Taxonomy Manager intefrace.
   *
   * @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\taxonomy\VocabularyInterface $taxonomy_vocabulary
   *   The vocabulary being with worked with.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL) {

    // Advagg clash warning.
    if ($this->moduleHandler
      ->moduleExists('advagg')) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('<em>Advanced CSS/JS Aggregation</em> module is enabled. Make sure that <em>%settings_link</em> setting is switched off.', [
        '%settings_link' => $this->linkGenerator
          ->generate($this
          ->t('Move all external scripts to the top of the execution order'), new Url('advagg_mod.settings')),
      ]));
    }

    // Build the form.
    $form['voc'] = [
      '#type' => 'value',
      "#value" => $taxonomy_vocabulary,
    ];
    $form['#attached']['library'][] = 'taxonomy_manager/form';
    if (TaxonomyManagerHelper::vocabularyIsEmpty($taxonomy_vocabulary
      ->id())) {
      $form['text'] = [
        '#markup' => $this
          ->t('No terms available'),
      ];
      $form[] = $this->formBuilder
        ->getForm('Drupal\\taxonomy_manager\\Form\\AddTermsToVocabularyForm', $taxonomy_vocabulary);
      return $form;
    }
    $form['toolbar'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Toolbar'),
    ];
    $form['toolbar']['add'] = [
      '#type' => 'submit',
      '#name' => 'add',
      '#value' => $this
        ->t('Add'),
      '#ajax' => [
        'callback' => '::addFormCallback',
      ],
    ];
    $form['toolbar']['delete'] = [
      '#type' => 'submit',
      '#name' => 'delete',
      '#value' => $this
        ->t('Delete'),
      '#attributes' => [
        'disabled' => TRUE,
      ],
      '#ajax' => [
        'callback' => '::deleteFormCallback',
      ],
    ];
    $form['toolbar']['move'] = [
      '#type' => 'submit',
      '#name' => 'move',
      '#value' => $this
        ->t('Move'),
      '#ajax' => [
        'callback' => '::moveFormCallback',
      ],
    ];
    $form['toolbar']['export'] = [
      '#type' => 'submit',
      '#name' => 'export',
      '#value' => $this
        ->t('Export'),
      '#ajax' => [
        'callback' => '::exportFormCallback',
      ],
    ];

    /* Taxonomy manager. */
    $form['taxonomy']['#tree'] = TRUE;
    $form['taxonomy']['manager'] = [
      '#type' => 'fieldset',
      '#title' => Html::escape($taxonomy_vocabulary
        ->label()),
      '#tree' => TRUE,
    ];
    $form['taxonomy']['manager']['top'] = [
      '#markup' => '',
      '#prefix' => '<div class="taxonomy-manager-tree-top">',
      '#suffix' => '</div>',
    ];
    $form['taxonomy']['manager']['tree'] = [
      '#type' => 'taxonomy_manager_tree',
      '#vocabulary' => $taxonomy_vocabulary
        ->id(),
      '#pager_size' => $this->configFactory
        ->get('taxonomy_manager.settings')
        ->get('taxonomy_manager_pager_tree_page_size'),
    ];
    $form['taxonomy']['manager']['pager'] = [
      '#type' => 'pager',
    ];

    // Add placeholder for term data form, the load-term-data field has AJAX
    // events attached and will trigger the load of the term data form. The
    // field is hidden via CSS and the value gets set in termData.js.
    $form['term-data']['#prefix'] = '<div id="taxonomy-term-data-form">';
    $form['term-data']['#suffix'] = '</div>';
    $form['load-term-data'] = [
      '#type' => 'textfield',
      '#ajax' => [
        'callback' => '::termDataCallback',
        'event' => 'change',
      ],
    ];
    return $form;
  }

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

    // $selected_terms = $form_state->getValue(['taxonomy', 'manager', 'tree']);.
  }

  /**
   * AJAX callback handler for add form.
   */
  public function addFormCallback($form, FormStateInterface $form_state) {
    return $this
      ->modalHelper($form_state, 'Drupal\\taxonomy_manager\\Form\\AddTermsToVocabularyForm', 'taxonomy_manager.admin_vocabulary.add', $this
      ->t('Add terms'));
  }

  /**
   * AJAX callback handler for delete form.
   */
  public function deleteFormCallback($form, FormStateInterface $form_state) {
    return $this
      ->modalHelper($form_state, 'Drupal\\taxonomy_manager\\Form\\DeleteTermsForm', 'taxonomy_manager.admin_vocabulary.delete', $this
      ->t('Delete terms'));
  }

  /**
   * AJAX callback handler for move form.
   */
  public function moveFormCallback($form, FormStateInterface $form_state) {
    return $this
      ->modalHelper($form_state, 'Drupal\\taxonomy_manager\\Form\\MoveTermsForm', 'taxonomy_manager.admin_vocabulary.move', $this
      ->t('Move terms'));
  }

  /**
   * AJAX callback handler for export terms from a given vocabulary.
   */
  public function exportFormCallback($form, FormStateInterface $form_state) {
    return $this
      ->modalHelper($form_state, 'Drupal\\taxonomy_manager\\Form\\ExportTermsForm', 'taxonomy_manager.admin_vocabulary.export', $this
      ->t('Export terms'));
  }

  /**
   * AJAX callback handler for the term data form.
   */
  public function termDataCallback($form, FormStateInterface $form_state) {
    $taxonomy_term = $this->entityTypeManager
      ->getStorage('taxonomy_term')
      ->load($form_state
      ->getValue('load-term-data'));
    $term_form = $this->entityFormBuilder
      ->getForm($taxonomy_term, 'default');

    // Move the term data form into a fieldset.
    $term_form['fieldset']['#type'] = 'fieldset';
    $term_form['fieldset']['#title'] = Html::escape($taxonomy_term
      ->getName()) . ' (' . $taxonomy_term
      ->id() . ')';
    $term_form['fieldset']['#attributes'] = [];
    foreach (Element::children($term_form) as $key) {
      if ($key != 'fieldset') {
        $term_form['fieldset'][$key] = $term_form[$key];
        unset($term_form[$key]);
      }
    }
    $term_form['#prefix'] = '<div id="taxonomy-term-data-form">';
    $term_form['#suffix'] = '</div>';
    $current_path = $this->currentPath
      ->getPath();

    // Change the form action url form the current site to the add form.
    $term_form['#action'] = $this->urlGenerator
      ->generateFromRoute('entity.taxonomy_term.edit_form', [
      'taxonomy_term' => $taxonomy_term
        ->id(),
    ], [
      'query' => [
        'destination' => $current_path,
      ],
    ]);
    $response = new AjaxResponse();
    $response
      ->addCommand(new ReplaceCommand('#taxonomy-term-data-form', $term_form));
    return $response;
  }

  /**
   * Term data submit handler.
   *
   * @TODO: redirect to taxonomy manager
   */
  public static function termDataFormSubmit($form, FormStateInterface $form_state) {
  }

  /**
   * Helper function to generate a modal form within an AJAX callback.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state of the current (parent) form.
   * @param string $class_name
   *   The class name of the form to embed in the modal.
   * @param string $route_name
   *   The route name the form is located.
   * @param string $title
   *   The modal title.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The ajax response.
   */
  protected function modalHelper(FormStateInterface $form_state, $class_name, $route_name, $title) {
    $taxonomy_vocabulary = $form_state
      ->getValue('voc');
    $selected_terms = $form_state
      ->getValue([
      'taxonomy',
      'manager',
      'tree',
    ]);
    $del_form = $this->formBuilder
      ->getForm($class_name, $taxonomy_vocabulary, $selected_terms);
    $del_form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    // Change the form action url form the current site to the add form.
    $del_form['#action'] = $this
      ->url($route_name, [
      'taxonomy_vocabulary' => $taxonomy_vocabulary
        ->id(),
    ]);
    $response = new AjaxResponse();
    $response
      ->addCommand(new OpenModalDialogCommand($title, $del_form, [
      'width' => '700',
    ]));
    return $response;
  }

}

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::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.
TaxonomyManagerForm::$entityFormBuilder protected property The entity form builder.
TaxonomyManagerForm::$entityTypeManager protected property The entity type manager.
TaxonomyManagerForm::$formBuilder protected property The form builder service.
TaxonomyManagerForm::$linkGenerator protected property The link generator. Overrides LinkGeneratorTrait::$linkGenerator
TaxonomyManagerForm::$moduleHandler protected property The module handler.
TaxonomyManagerForm::$urlGenerator protected property The url generator. Overrides UrlGeneratorTrait::$urlGenerator
TaxonomyManagerForm::addFormCallback public function AJAX callback handler for add form.
TaxonomyManagerForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
TaxonomyManagerForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TaxonomyManagerForm::deleteFormCallback public function AJAX callback handler for delete form.
TaxonomyManagerForm::exportFormCallback public function AJAX callback handler for export terms from a given vocabulary.
TaxonomyManagerForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
TaxonomyManagerForm::getTitle public function Returns the title for the whole page.
TaxonomyManagerForm::modalHelper protected function Helper function to generate a modal form within an AJAX callback.
TaxonomyManagerForm::moveFormCallback public function AJAX callback handler for move form.
TaxonomyManagerForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
TaxonomyManagerForm::termDataCallback public function AJAX callback handler for the term data form.
TaxonomyManagerForm::termDataFormSubmit public static function Term data submit handler.
TaxonomyManagerForm::__construct public function Constructs a \Drupal\taxonomy_manager\Form\TaxonomyManagerForm object.
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.