You are here

taxonomy_multidelete_terms.module in Taxonomy Multi-delete Terms 8

Control taxonomy term delete.

File

taxonomy_multidelete_terms.module
View source
<?php

/**
 * @file
 * Control taxonomy term delete.
 */
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Link;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Implements hook_help().
 */
function taxonomy_multidelete_terms_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.taxonomy_multidelete_terms':
      return '<p>' . t('This module help to delete multiple term at one time.<br>You just need to select terms and click on delete button.</br>All selected terms will be delete. You can also delete all terms at one time.') . '</p>';
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function taxonomy_multidelete_terms_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'taxonomy_overview_terms') {
    $checkboxes_present = FALSE;
    $user = \Drupal::currentUser();

    //Exit now if we don't have permissions to multi-delete
    if (!$user
      ->hasPermission('access taxonomy multidelete terms')) {
      return;
    }
    $vocabulary = $form_state
      ->get([
      'taxonomy',
      'vocabulary',
    ]);
    $tree = \Drupal::service('entity_type.manager')
      ->getStorage("taxonomy_term")
      ->loadTree($vocabulary
      ->id(), 0, NULL, TRUE);
    $term_id = array();
    foreach ($tree as $term) {
      $term_id[] = $term
        ->id();
    }
    foreach ($form['terms'] as $key => $element) {

      //If the weight field is present, then the vocabulary is in a state where it can be updated.
      if (substr($key, 0, 4) === 'tid:' && isset($form['terms'][$key]['weight'])) {
        $checkboxes_present = TRUE;

        //Add delete checkbox to table
        $form['terms'][$key]['term']['check-delete'] = [
          '#type' => 'checkbox',
          '#title' => Link::fromTextAndUrl($form['terms'][$key]['term']['#title'], $form['terms'][$key]['term']['#url'])
            ->toString(),
        ];
        if (count($term_id) == 1) {
          $form['terms'][$key]['term']['tid'] = array(
            '#type' => 'hidden',
            '#value' => $term_id[0],
            '#attributes' => array(
              'class' => array(
                'term-id',
              ),
            ),
          );
          $form['terms'][$key]['term']['depth'] = array(
            '#type' => 'hidden',
            '#default_value' => 0,
            '#attributes' => array(
              'class' => array(
                'term-depth',
              ),
            ),
          );
        }

        //Change root item from a link to a container to avoid showing links twice.
        unset($form['terms'][$key]['term']['#title']);
        unset($form['terms'][$key]['term']['#url']);
        $form['terms'][$key]['term']['#type'] = "container";
      }
    }

    //Make sure we rendered at least one checkbox before adding the delete button and select all header option.
    if ($checkboxes_present) {

      //Add 'select all' checkbox to the header. Width auto because select all assumes it's the only thing in the column
      $form['terms']['#header']['term'] = [
        'data' => Markup::create('&nbsp;&nbsp;' . t('Name')),
        'class' => [
          'select-all',
        ],
        'style' => 'width:auto;',
      ];
      $form['actions']['delete'] = [
        '#type' => 'submit',
        '#value' => t('Delete'),
        '#submit' => [
          'taxonomy_multidelete_terms_taxonomy_overview_terms_submit',
        ],
      ];
      $form['#validate'][] = 'taxonomy_multidelete_terms_taxonomy_overview_terms_validate';
      $form['#attached']['library'][] = 'core/drupal.tableselect';
    }
  }
}

/**
 * Validate form to delete terms.
 */
function taxonomy_multidelete_terms_taxonomy_overview_terms_validate(&$form, FormStateInterface $form_state) {
  if ($form_state
    ->getTriggeringElement()['#parents'][0] === 'delete') {
    $vocabulary = $form_state
      ->get([
      'taxonomy',
      'vocabulary',
    ]);
    $tree = \Drupal::service('entity_type.manager')
      ->getStorage("taxonomy_term")
      ->loadTree($vocabulary
      ->id(), 0, NULL, TRUE);
    $deleted_term_array = taxonomy_multidelete_terms_get_deleted_term_names($tree, $form_state);
    if (count($deleted_term_array) === 0) {
      $form_state
        ->setErrorByName('', t('Please select term(s) to delete.'));
    }
  }
}

/**
 * Submit form to delete terms.
 */
function taxonomy_multidelete_terms_taxonomy_overview_terms_submit(&$form, FormStateInterface $form_state) {
  $vocabulary = $form_state
    ->get([
    'taxonomy',
    'vocabulary',
  ]);
  $url = Url::fromRoute('taxonomy_multidelete_terms.delete', [
    'taxonomy_vocabulary' => $vocabulary
      ->id(),
  ]);
  $tempstore = \Drupal::service('user.private_tempstore')
    ->get('taxonomy_multidelete_terms');
  $tempstore
    ->set('deletedterms', $form_state
    ->getValue('terms'));
  $tempstore
    ->set('vocabulary', Vocabulary::load($vocabulary
    ->id())
    ->get('vid'));
  $form_state
    ->setRedirectUrl($url);
}

/**
 * It will return name of the term name Which are deleted.
 */
function taxonomy_multidelete_terms_get_deleted_term_names($tree, $form_state = NULL, $preseleted = NULL) {
  $name = [];
  if (!empty($preseleted)) {
    foreach ($tree as $term) {
      $name[] = Term::load($term)
        ->get('name')->value;
    }
  }
  else {
    foreach ($form_state
      ->getValue('terms') as $values) {
      if (!empty($values['term']['check-delete'])) {
        $seleted_tid = $values['term']['tid'];
        $name[] = Term::load($seleted_tid)
          ->get('name')->value;
      }
    }
  }
  return $name;
}