OverviewTerms.php 18 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\taxonomy\Form;

5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Entity\EntityManagerInterface;
7 8
use Drupal\Core\Form\FormBase;
use Drupal\Core\Extension\ModuleHandlerInterface;
9
use Drupal\Core\Form\FormStateInterface;
10 11
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
12 13 14
use Drupal\taxonomy\VocabularyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

15
/**
16
 * Provides terms overview form for a taxonomy vocabulary.
17 18
 *
 * @internal
19 20 21 22 23 24 25 26 27 28
 */
class OverviewTerms extends FormBase {

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

29 30 31 32 33 34 35
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

36
  /**
37
   * The term storage handler.
38 39 40 41 42
   *
   * @var \Drupal\taxonomy\TermStorageInterface
   */
  protected $storageController;

43 44 45 46 47 48 49 50 51 52 53 54 55 56
  /**
   * The term list builder.
   *
   * @var \Drupal\Core\Entity\EntityListBuilderInterface
   */
  protected $termListBuilder;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

57 58 59 60 61
  /**
   * Constructs an OverviewTerms object.
   *
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
62 63
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager service.
64 65
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
66
   */
67
  public function __construct(ModuleHandlerInterface $module_handler, EntityManagerInterface $entity_manager, RendererInterface $renderer = NULL) {
68
    $this->moduleHandler = $module_handler;
69
    $this->entityManager = $entity_manager;
70
    $this->storageController = $entity_manager->getStorage('taxonomy_term');
71 72
    $this->termListBuilder = $entity_manager->getListBuilder('taxonomy_term');
    $this->renderer = $renderer ?: \Drupal::service('renderer');
73 74 75 76 77 78 79
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
80
      $container->get('module_handler'),
81 82
      $container->get('entity.manager'),
      $container->get('renderer')
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    );
  }

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

  /**
   * Form constructor.
   *
   * Display a tree of all the terms in a vocabulary, with options to edit
   * each one. The form is made drag and drop by the theme function.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
101 102
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
103 104 105 106 107 108
   * @param \Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary
   *   The vocabulary to display the overview form for.
   *
   * @return array
   *   The form structure.
   */
109
  public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL) {
110 111
    // @todo Remove global variables when https://www.drupal.org/node/2044435 is
    //   in.
112 113
    global $pager_page_array, $pager_total, $pager_total_items;

114
    $form_state->set(['taxonomy', 'vocabulary'], $taxonomy_vocabulary);
115 116 117 118
    $parent_fields = FALSE;

    $page = $this->getRequest()->query->get('page') ?: 0;
    // Number of terms per page.
119
    $page_increment = $this->config('taxonomy.settings')->get('terms_per_page_admin');
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    // Elements shown on this page.
    $page_entries = 0;
    // Elements at the root level before this page.
    $before_entries = 0;
    // Elements at the root level after this page.
    $after_entries = 0;
    // Elements at the root level on this page.
    $root_entries = 0;

    // Terms from previous and next pages are shown if the term tree would have
    // been cut in the middle. Keep track of how many extra terms we show on
    // each page of terms.
    $back_step = NULL;
    $forward_step = 0;

    // An array of the terms to be displayed on this page.
136
    $current_page = [];
137 138

    $delta = 0;
139
    $term_deltas = [];
140
    $tree = $this->storageController->loadTree($taxonomy_vocabulary->id(), 0, NULL, TRUE);
141
    $tree_index = 0;
142 143
    do {
      // In case this tree is completely empty.
144
      if (empty($tree[$tree_index])) {
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        break;
      }
      $delta++;
      // Count entries before the current page.
      if ($page && ($page * $page_increment) > $before_entries && !isset($back_step)) {
        $before_entries++;
        continue;
      }
      // Count entries after the current page.
      elseif ($page_entries > $page_increment && isset($complete_tree)) {
        $after_entries++;
        continue;
      }

      // Do not let a term start the page that is not at the root.
160
      $term = $tree[$tree_index];
161 162
      if (isset($term->depth) && ($term->depth > 0) && !isset($back_step)) {
        $back_step = 0;
163
        while ($pterm = $tree[--$tree_index]) {
164 165 166
          $before_entries--;
          $back_step++;
          if ($pterm->depth == 0) {
167
            $tree_index--;
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            // Jump back to the start of the root level parent.
            continue 2;
          }
        }
      }
      $back_step = isset($back_step) ? $back_step : 0;

      // Continue rendering the tree until we reach the a new root item.
      if ($page_entries >= $page_increment + $back_step + 1 && $term->depth == 0 && $root_entries > 1) {
        $complete_tree = TRUE;
        // This new item at the root level is the first item on the next page.
        $after_entries++;
        continue;
      }
      if ($page_entries >= $page_increment + $back_step) {
        $forward_step++;
      }

      // Finally, if we've gotten down this far, we're rendering a term on this
      // page.
      $page_entries++;
      $term_deltas[$term->id()] = isset($term_deltas[$term->id()]) ? $term_deltas[$term->id()] + 1 : 0;
      $key = 'tid:' . $term->id() . ':' . $term_deltas[$term->id()];

      // Keep track of the first term displayed on this page.
      if ($page_entries == 1) {
        $form['#first_tid'] = $term->id();
      }
      // Keep a variable to make sure at least 2 root elements are displayed.
      if ($term->parents[0] == 0) {
        $root_entries++;
      }
      $current_page[$key] = $term;
201
    } while (isset($tree[++$tree_index]));
202 203 204 205 206 207 208 209 210 211

    // Because we didn't use a pager query, set the necessary pager variables.
    $total_entries = $before_entries + $page_entries + $after_entries;
    $pager_total_items[0] = $total_entries;
    $pager_page_array[0] = $page;
    $pager_total[0] = ceil($total_entries / $page_increment);

    // If this form was already submitted once, it's probably hit a validation
    // error. Ensure the form is rebuilt in the same order as the user
    // submitted.
212 213
    $user_input = $form_state->getUserInput();
    if (!empty($user_input)) {
214
      // Get the POST order.
215
      $order = array_flip(array_keys($user_input['terms']));
216 217 218 219 220
      // Update our form with the new order.
      $current_page = array_merge($order, $current_page);
      foreach ($current_page as $key => $term) {
        // Verify this is a term for the current page and set at the current
        // depth.
221 222
        if (is_array($user_input['terms'][$key]) && is_numeric($user_input['terms'][$key]['term']['tid'])) {
          $current_page[$key]->depth = $user_input['terms'][$key]['term']['depth'];
223 224 225 226 227 228 229
        }
        else {
          unset($current_page[$key]);
        }
      }
    }

230
    $errors = $form_state->getErrors();
231 232
    $row_position = 0;
    // Build the actual form.
233 234 235 236 237 238 239 240
    $access_control_handler = $this->entityManager->getAccessControlHandler('taxonomy_term');
    $create_access = $access_control_handler->createAccess($taxonomy_vocabulary->id(), NULL, [], TRUE);
    if ($create_access->isAllowed()) {
      $empty = $this->t('No terms available. <a href=":link">Add term</a>.', [':link' => Url::fromRoute('entity.taxonomy_term.add_form', ['taxonomy_vocabulary' => $taxonomy_vocabulary->id()])->toString()]);
    }
    else {
      $empty = $this->t('No terms available.');
    }
241
    $form['terms'] = [
242
      '#type' => 'table',
243
      '#empty' => $empty,
244 245 246 247 248
      '#header' => [
        'term' => $this->t('Name'),
        'operations' => $this->t('Operations'),
        'weight' => $this->t('Weight'),
      ],
249
      '#attributes' => [
250
        'id' => 'taxonomy',
251 252
      ],
    ];
253 254 255 256 257
    $this->renderer->addCacheableDependency($form['terms'], $create_access);

    // Only allow access to changing weights if the user has update access for
    // all terms.
    $change_weight_access = AccessResult::allowed();
258
    foreach ($current_page as $key => $term) {
259 260 261 262 263
      $form['terms'][$key] = [
        'term' => [],
        'operations' => [],
        'weight' => [],
      ];
264
      /** @var $term \Drupal\Core\Entity\EntityInterface */
265
      $term = $this->entityManager->getTranslationFromContext($term);
266
      $form['terms'][$key]['#term'] = $term;
267
      $indentation = [];
268
      if (isset($term->depth) && $term->depth > 0) {
269
        $indentation = [
270 271
          '#theme' => 'indentation',
          '#size' => $term->depth,
272
        ];
273
      }
274
      $form['terms'][$key]['term'] = [
275
        '#prefix' => !empty($indentation) ? \Drupal::service('renderer')->render($indentation) : '',
276
        '#type' => 'link',
277
        '#title' => $term->getName(),
278
        '#url' => $term->urlInfo(),
279
      ];
280
      if ($taxonomy_vocabulary->getHierarchy() != VocabularyInterface::HIERARCHY_MULTIPLE && count($tree) > 1) {
281
        $parent_fields = TRUE;
282
        $form['terms'][$key]['term']['tid'] = [
283 284
          '#type' => 'hidden',
          '#value' => $term->id(),
285 286 287 288 289
          '#attributes' => [
            'class' => ['term-id'],
          ],
        ];
        $form['terms'][$key]['term']['parent'] = [
290 291 292
          '#type' => 'hidden',
          // Yes, default_value on a hidden. It needs to be changeable by the
          // javascript.
293
          '#default_value' => $term->parents[0],
294 295 296 297 298
          '#attributes' => [
            'class' => ['term-parent'],
          ],
        ];
        $form['terms'][$key]['term']['depth'] = [
299 300 301 302
          '#type' => 'hidden',
          // Same as above, the depth is modified by javascript, so it's a
          // default_value.
          '#default_value' => $term->depth,
303 304 305 306
          '#attributes' => [
            'class' => ['term-depth'],
          ],
        ];
307
      }
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
      $update_access = $term->access('update', NULL, TRUE);
      $change_weight_access = $change_weight_access->andIf($update_access);

      if ($update_access->isAllowed()) {
        $form['terms'][$key]['weight'] = [
          '#type' => 'weight',
          '#delta' => $delta,
          '#title' => $this->t('Weight for added term'),
          '#title_display' => 'invisible',
          '#default_value' => $term->getWeight(),
          '#attributes' => ['class' => ['term-weight']],
        ];
      }

      if ($operations = $this->termListBuilder->getOperations($term)) {
        $form['terms'][$key]['operations'] = [
          '#type' => 'operations',
          '#links' => $operations,
326
        ];
327 328
      }

329
      $form['terms'][$key]['#attributes']['class'] = [];
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
      if ($parent_fields) {
        $form['terms'][$key]['#attributes']['class'][] = 'draggable';
      }

      // Add classes that mark which terms belong to previous and next pages.
      if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) {
        $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-preview';
      }

      if ($row_position !== 0 && $row_position !== count($tree) - 1) {
        if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) {
          $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-top';
        }
        elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
          $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom';
        }
      }

      // Add an error class if this row contains a form error.
      foreach ($errors as $error_key => $error) {
        if (strpos($error_key, $key) === 0) {
          $form['terms'][$key]['#attributes']['class'][] = 'error';
        }
      }
      $row_position++;
    }

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    $this->renderer->addCacheableDependency($form['terms'], $change_weight_access);
    if ($change_weight_access->isAllowed()) {
      if ($parent_fields) {
        $form['terms']['#tabledrag'][] = [
          'action' => 'match',
          'relationship' => 'parent',
          'group' => 'term-parent',
          'subgroup' => 'term-parent',
          'source' => 'term-id',
          'hidden' => FALSE,
        ];
        $form['terms']['#tabledrag'][] = [
          'action' => 'depth',
          'relationship' => 'group',
          'group' => 'term-depth',
          'hidden' => FALSE,
        ];
        $form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy';
        $form['terms']['#attached']['drupalSettings']['taxonomy'] = [
          'backStep' => $back_step,
          'forwardStep' => $forward_step,
        ];
      }
380
      $form['terms']['#tabledrag'][] = [
381 382 383
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'term-weight',
384
      ];
385 386
    }

387
    if (($taxonomy_vocabulary->getHierarchy() !== VocabularyInterface::HIERARCHY_MULTIPLE && count($tree) > 1) && $change_weight_access->isAllowed()) {
388 389
      $form['actions'] = ['#type' => 'actions', '#tree' => FALSE];
      $form['actions']['submit'] = [
390 391 392
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#button_type' => 'primary',
393 394
      ];
      $form['actions']['reset_alphabetical'] = [
395
        '#type' => 'submit',
396
        '#submit' => ['::submitReset'],
397
        '#value' => $this->t('Reset to alphabetical'),
398
      ];
399 400
    }

401
    $form['pager_pager'] = ['#type' => 'pager'];
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    return $form;
  }

  /**
   * Form submission handler.
   *
   * Rather than using a textfield or weight field, this form depends entirely
   * upon the order of form elements on the page to determine new weights.
   *
   * Because there might be hundreds or thousands of taxonomy terms that need to
   * be ordered, terms are weighted from 0 to the number of terms in the
   * vocabulary, rather than the standard -10 to 10 scale. Numbers are sorted
   * lowest to highest, but are not necessarily sequential. Numbers may be
   * skipped when a term has children so that reordering is minimal when a child
   * is added or removed from a term.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
420 421
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
422
   */
423
  public function submitForm(array &$form, FormStateInterface $form_state) {
424
    // Sort term order based on weight.
425
    uasort($form_state->getValue('terms'), ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
426

427
    $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
428
    // Update the current hierarchy type as we go.
429
    $hierarchy = VocabularyInterface::HIERARCHY_DISABLED;
430

431
    $changed_terms = [];
432
    $tree = $this->storageController->loadTree($vocabulary->id(), 0, NULL, TRUE);
433 434 435 436 437 438 439 440 441

    if (empty($tree)) {
      return;
    }

    // Build a list of all terms that need to be updated on previous pages.
    $weight = 0;
    $term = $tree[0];
    while ($term->id() != $form['#first_tid']) {
442 443
      if ($term->parents[0] == 0 && $term->getWeight() != $weight) {
        $term->setWeight($weight);
444 445 446
        $changed_terms[$term->id()] = $term;
      }
      $weight++;
447
      $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
448 449 450 451
      $term = $tree[$weight];
    }

    // Renumber the current page weights and assign any new parents.
452
    $level_weights = [];
453
    foreach ($form_state->getValue('terms') as $tid => $values) {
454 455 456
      if (isset($form['terms'][$tid]['#term'])) {
        $term = $form['terms'][$tid]['#term'];
        // Give terms at the root level a weight in sequence with terms on previous pages.
457 458
        if ($values['term']['parent'] == 0 && $term->getWeight() != $weight) {
          $term->setWeight($weight);
459 460 461 462
          $changed_terms[$term->id()] = $term;
        }
        // Terms not at the root level can safely start from 0 because they're all on this page.
        elseif ($values['term']['parent'] > 0) {
463
          $level_weights[$values['term']['parent']] = isset($level_weights[$values['term']['parent']]) ? $level_weights[$values['term']['parent']] + 1 : 0;
464 465
          if ($level_weights[$values['term']['parent']] != $term->getWeight()) {
            $term->setWeight($level_weights[$values['term']['parent']]);
466 467 468 469
            $changed_terms[$term->id()] = $term;
          }
        }
        // Update any changed parents.
470
        if ($values['term']['parent'] != $term->parents[0]) {
471
          $term->parent->target_id = $values['term']['parent'];
472 473
          $changed_terms[$term->id()] = $term;
        }
474
        $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
475 476 477 478 479 480 481
        $weight++;
      }
    }

    // Build a list of all terms that need to be updated on following pages.
    for ($weight; $weight < count($tree); $weight++) {
      $term = $tree[$weight];
482
      if ($term->parents[0] == 0 && $term->getWeight() != $weight) {
483
        $term->parent->target_id = $term->parents[0];
484
        $term->setWeight($weight);
485 486
        $changed_terms[$term->id()] = $term;
      }
487
      $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
488 489 490 491 492 493 494 495
    }

    // Save all updated terms.
    foreach ($changed_terms as $term) {
      $term->save();
    }

    // Update the vocabulary hierarchy to flat or single hierarchy.
496 497
    if ($vocabulary->getHierarchy() != $hierarchy) {
      $vocabulary->setHierarchy($hierarchy);
498 499
      $vocabulary->save();
    }
500
    $this->messenger()->addStatus($this->t('The configuration options have been saved.'));
501 502 503 504 505
  }

  /**
   * Redirects to confirmation form for the reset action.
   */
506
  public function submitReset(array &$form, FormStateInterface $form_state) {
507
    /** @var $vocabulary \Drupal\taxonomy\VocabularyInterface */
508
    $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
509
    $form_state->setRedirectUrl($vocabulary->urlInfo('reset-form'));
510 511 512
  }

}