3 namespace Drupal\taxonomy\Form;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Entity\EntityManagerInterface;
7 use Drupal\Core\Form\FormBase;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\Core\Form\FormStateInterface;
10 use Drupal\Core\Render\RendererInterface;
12 use Drupal\taxonomy\VocabularyInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
16 * Provides terms overview form for a taxonomy vocabulary.
20 class OverviewTerms extends FormBase {
23 * The module handler service.
25 * @var \Drupal\Core\Extension\ModuleHandlerInterface
27 protected $moduleHandler;
32 * @var \Drupal\Core\Entity\EntityManagerInterface
34 protected $entityManager;
37 * The term storage handler.
39 * @var \Drupal\taxonomy\TermStorageInterface
41 protected $storageController;
44 * The term list builder.
46 * @var \Drupal\Core\Entity\EntityListBuilderInterface
48 protected $termListBuilder;
51 * The renderer service.
53 * @var \Drupal\Core\Render\RendererInterface
58 * Constructs an OverviewTerms object.
60 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
61 * The module handler service.
62 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
63 * The entity manager service.
64 * @param \Drupal\Core\Render\RendererInterface $renderer
65 * The renderer service.
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 $this->termListBuilder = $entity_manager->getListBuilder('taxonomy_term');
72 $this->renderer = $renderer ?: \Drupal::service('renderer');
78 public static function create(ContainerInterface $container) {
80 $container->get('module_handler'),
81 $container->get('entity.manager'),
82 $container->get('renderer')
89 public function getFormId() {
90 return 'taxonomy_overview_terms';
96 * Display a tree of all the terms in a vocabulary, with options to edit
97 * each one. The form is made drag and drop by the theme function.
100 * An associative array containing the structure of the form.
101 * @param \Drupal\Core\Form\FormStateInterface $form_state
102 * The current state of the form.
103 * @param \Drupal\taxonomy\VocabularyInterface $taxonomy_vocabulary
104 * The vocabulary to display the overview form for.
107 * The form structure.
109 public function buildForm(array $form, FormStateInterface $form_state, VocabularyInterface $taxonomy_vocabulary = NULL) {
110 // @todo Remove global variables when https://www.drupal.org/node/2044435 is
112 global $pager_page_array, $pager_total, $pager_total_items;
114 $form_state->set(['taxonomy', 'vocabulary'], $taxonomy_vocabulary);
115 $parent_fields = FALSE;
117 $page = $this->getRequest()->query->get('page') ?: 0;
118 // Number of terms per page.
119 $page_increment = $this->config('taxonomy.settings')->get('terms_per_page_admin');
120 // Elements shown on this page.
122 // Elements at the root level before this page.
124 // Elements at the root level after this page.
126 // Elements at the root level on this page.
129 // Terms from previous and next pages are shown if the term tree would have
130 // been cut in the middle. Keep track of how many extra terms we show on
131 // each page of terms.
135 // An array of the terms to be displayed on this page.
140 $tree = $this->storageController->loadTree($taxonomy_vocabulary->id(), 0, NULL, TRUE);
143 // In case this tree is completely empty.
144 if (empty($tree[$tree_index])) {
148 // Count entries before the current page.
149 if ($page && ($page * $page_increment) > $before_entries && !isset($back_step)) {
153 // Count entries after the current page.
154 elseif ($page_entries > $page_increment && isset($complete_tree)) {
159 // Do not let a term start the page that is not at the root.
160 $term = $tree[$tree_index];
161 if (isset($term->depth) && ($term->depth > 0) && !isset($back_step)) {
163 while ($pterm = $tree[--$tree_index]) {
166 if ($pterm->depth == 0) {
168 // Jump back to the start of the root level parent.
173 $back_step = isset($back_step) ? $back_step : 0;
175 // Continue rendering the tree until we reach the a new root item.
176 if ($page_entries >= $page_increment + $back_step + 1 && $term->depth == 0 && $root_entries > 1) {
177 $complete_tree = TRUE;
178 // This new item at the root level is the first item on the next page.
182 if ($page_entries >= $page_increment + $back_step) {
186 // Finally, if we've gotten down this far, we're rendering a term on this
189 $term_deltas[$term->id()] = isset($term_deltas[$term->id()]) ? $term_deltas[$term->id()] + 1 : 0;
190 $key = 'tid:' . $term->id() . ':' . $term_deltas[$term->id()];
192 // Keep track of the first term displayed on this page.
193 if ($page_entries == 1) {
194 $form['#first_tid'] = $term->id();
196 // Keep a variable to make sure at least 2 root elements are displayed.
197 if ($term->parents[0] == 0) {
200 $current_page[$key] = $term;
201 } while (isset($tree[++$tree_index]));
203 // Because we didn't use a pager query, set the necessary pager variables.
204 $total_entries = $before_entries + $page_entries + $after_entries;
205 $pager_total_items[0] = $total_entries;
206 $pager_page_array[0] = $page;
207 $pager_total[0] = ceil($total_entries / $page_increment);
209 // If this form was already submitted once, it's probably hit a validation
210 // error. Ensure the form is rebuilt in the same order as the user
212 $user_input = $form_state->getUserInput();
213 if (!empty($user_input)) {
214 // Get the POST order.
215 $order = array_flip(array_keys($user_input['terms']));
216 // Update our form with the new order.
217 $current_page = array_merge($order, $current_page);
218 foreach ($current_page as $key => $term) {
219 // Verify this is a term for the current page and set at the current
221 if (is_array($user_input['terms'][$key]) && is_numeric($user_input['terms'][$key]['term']['tid'])) {
222 $current_page[$key]->depth = $user_input['terms'][$key]['term']['depth'];
225 unset($current_page[$key]);
230 $errors = $form_state->getErrors();
232 // Build the actual form.
233 $access_control_handler = $this->entityManager->getAccessControlHandler('taxonomy_term');
234 $create_access = $access_control_handler->createAccess($taxonomy_vocabulary->id(), NULL, [], TRUE);
235 if ($create_access->isAllowed()) {
236 $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()]);
239 $empty = $this->t('No terms available.');
245 'term' => $this->t('Name'),
246 'operations' => $this->t('Operations'),
247 'weight' => $this->t('Weight'),
253 $this->renderer->addCacheableDependency($form['terms'], $create_access);
255 // Only allow access to changing weights if the user has update access for
257 $change_weight_access = AccessResult::allowed();
258 foreach ($current_page as $key => $term) {
259 $form['terms'][$key] = [
264 /** @var $term \Drupal\Core\Entity\EntityInterface */
265 $term = $this->entityManager->getTranslationFromContext($term);
266 $form['terms'][$key]['#term'] = $term;
268 if (isset($term->depth) && $term->depth > 0) {
270 '#theme' => 'indentation',
271 '#size' => $term->depth,
274 $form['terms'][$key]['term'] = [
275 '#prefix' => !empty($indentation) ? \Drupal::service('renderer')->render($indentation) : '',
277 '#title' => $term->getName(),
278 '#url' => $term->urlInfo(),
280 if ($taxonomy_vocabulary->getHierarchy() != VocabularyInterface::HIERARCHY_MULTIPLE && count($tree) > 1) {
281 $parent_fields = TRUE;
282 $form['terms'][$key]['term']['tid'] = [
284 '#value' => $term->id(),
286 'class' => ['term-id'],
289 $form['terms'][$key]['term']['parent'] = [
291 // Yes, default_value on a hidden. It needs to be changeable by the
293 '#default_value' => $term->parents[0],
295 'class' => ['term-parent'],
298 $form['terms'][$key]['term']['depth'] = [
300 // Same as above, the depth is modified by javascript, so it's a
302 '#default_value' => $term->depth,
304 'class' => ['term-depth'],
308 $update_access = $term->access('update', NULL, TRUE);
309 $change_weight_access = $change_weight_access->andIf($update_access);
311 if ($update_access->isAllowed()) {
312 $form['terms'][$key]['weight'] = [
315 '#title' => $this->t('Weight for added term'),
316 '#title_display' => 'invisible',
317 '#default_value' => $term->getWeight(),
318 '#attributes' => ['class' => ['term-weight']],
322 if ($operations = $this->termListBuilder->getOperations($term)) {
323 $form['terms'][$key]['operations'] = [
324 '#type' => 'operations',
325 '#links' => $operations,
329 $form['terms'][$key]['#attributes']['class'] = [];
330 if ($parent_fields) {
331 $form['terms'][$key]['#attributes']['class'][] = 'draggable';
334 // Add classes that mark which terms belong to previous and next pages.
335 if ($row_position < $back_step || $row_position >= $page_entries - $forward_step) {
336 $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-preview';
339 if ($row_position !== 0 && $row_position !== count($tree) - 1) {
340 if ($row_position == $back_step - 1 || $row_position == $page_entries - $forward_step - 1) {
341 $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-top';
343 elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
344 $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom';
348 // Add an error class if this row contains a form error.
349 foreach ($errors as $error_key => $error) {
350 if (strpos($error_key, $key) === 0) {
351 $form['terms'][$key]['#attributes']['class'][] = 'error';
357 $this->renderer->addCacheableDependency($form['terms'], $change_weight_access);
358 if ($change_weight_access->isAllowed()) {
359 if ($parent_fields) {
360 $form['terms']['#tabledrag'][] = [
362 'relationship' => 'parent',
363 'group' => 'term-parent',
364 'subgroup' => 'term-parent',
365 'source' => 'term-id',
368 $form['terms']['#tabledrag'][] = [
370 'relationship' => 'group',
371 'group' => 'term-depth',
374 $form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy';
375 $form['terms']['#attached']['drupalSettings']['taxonomy'] = [
376 'backStep' => $back_step,
377 'forwardStep' => $forward_step,
380 $form['terms']['#tabledrag'][] = [
382 'relationship' => 'sibling',
383 'group' => 'term-weight',
387 if (($taxonomy_vocabulary->getHierarchy() !== VocabularyInterface::HIERARCHY_MULTIPLE && count($tree) > 1) && $change_weight_access->isAllowed()) {
388 $form['actions'] = ['#type' => 'actions', '#tree' => FALSE];
389 $form['actions']['submit'] = [
391 '#value' => $this->t('Save'),
392 '#button_type' => 'primary',
394 $form['actions']['reset_alphabetical'] = [
396 '#submit' => ['::submitReset'],
397 '#value' => $this->t('Reset to alphabetical'),
401 $form['pager_pager'] = ['#type' => 'pager'];
406 * Form submission handler.
408 * Rather than using a textfield or weight field, this form depends entirely
409 * upon the order of form elements on the page to determine new weights.
411 * Because there might be hundreds or thousands of taxonomy terms that need to
412 * be ordered, terms are weighted from 0 to the number of terms in the
413 * vocabulary, rather than the standard -10 to 10 scale. Numbers are sorted
414 * lowest to highest, but are not necessarily sequential. Numbers may be
415 * skipped when a term has children so that reordering is minimal when a child
416 * is added or removed from a term.
419 * An associative array containing the structure of the form.
420 * @param \Drupal\Core\Form\FormStateInterface $form_state
421 * The current state of the form.
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']);
427 $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
428 // Update the current hierarchy type as we go.
429 $hierarchy = VocabularyInterface::HIERARCHY_DISABLED;
432 $tree = $this->storageController->loadTree($vocabulary->id(), 0, NULL, TRUE);
438 // Build a list of all terms that need to be updated on previous pages.
441 while ($term->id() != $form['#first_tid']) {
442 if ($term->parents[0] == 0 && $term->getWeight() != $weight) {
443 $term->setWeight($weight);
444 $changed_terms[$term->id()] = $term;
447 $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
448 $term = $tree[$weight];
451 // Renumber the current page weights and assign any new parents.
453 foreach ($form_state->getValue('terms') as $tid => $values) {
454 if (isset($form['terms'][$tid]['#term'])) {
455 $term = $form['terms'][$tid]['#term'];
456 // Give terms at the root level a weight in sequence with terms on previous pages.
457 if ($values['term']['parent'] == 0 && $term->getWeight() != $weight) {
458 $term->setWeight($weight);
459 $changed_terms[$term->id()] = $term;
461 // Terms not at the root level can safely start from 0 because they're all on this page.
462 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 if ($level_weights[$values['term']['parent']] != $term->getWeight()) {
465 $term->setWeight($level_weights[$values['term']['parent']]);
466 $changed_terms[$term->id()] = $term;
469 // Update any changed parents.
470 if ($values['term']['parent'] != $term->parents[0]) {
471 $term->parent->target_id = $values['term']['parent'];
472 $changed_terms[$term->id()] = $term;
474 $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
479 // Build a list of all terms that need to be updated on following pages.
480 for ($weight; $weight < count($tree); $weight++) {
481 $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 $changed_terms[$term->id()] = $term;
487 $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
490 // Save all updated terms.
491 foreach ($changed_terms as $term) {
495 // Update the vocabulary hierarchy to flat or single hierarchy.
496 if ($vocabulary->getHierarchy() != $hierarchy) {
497 $vocabulary->setHierarchy($hierarchy);
500 $this->messenger()->addStatus($this->t('The configuration options have been saved.'));
504 * 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'));