f9e0d595982e6ef0e299ea708bcf7115e9399212
[yaffs-website] / web / core / modules / taxonomy / src / Form / OverviewTerms.php
1 <?php
2
3 namespace Drupal\taxonomy\Form;
4
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;
11 use Drupal\Core\Url;
12 use Drupal\taxonomy\VocabularyInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14
15 /**
16  * Provides terms overview form for a taxonomy vocabulary.
17  *
18  * @internal
19  */
20 class OverviewTerms extends FormBase {
21
22   /**
23    * The module handler service.
24    *
25    * @var \Drupal\Core\Extension\ModuleHandlerInterface
26    */
27   protected $moduleHandler;
28
29   /**
30    * The entity manager.
31    *
32    * @var \Drupal\Core\Entity\EntityManagerInterface
33    */
34   protected $entityManager;
35
36   /**
37    * The term storage handler.
38    *
39    * @var \Drupal\taxonomy\TermStorageInterface
40    */
41   protected $storageController;
42
43   /**
44    * The term list builder.
45    *
46    * @var \Drupal\Core\Entity\EntityListBuilderInterface
47    */
48   protected $termListBuilder;
49
50   /**
51    * The renderer service.
52    *
53    * @var \Drupal\Core\Render\RendererInterface
54    */
55   protected $renderer;
56
57   /**
58    * Constructs an OverviewTerms object.
59    *
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.
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     $this->termListBuilder = $entity_manager->getListBuilder('taxonomy_term');
72     $this->renderer = $renderer ?: \Drupal::service('renderer');
73   }
74
75   /**
76    * {@inheritdoc}
77    */
78   public static function create(ContainerInterface $container) {
79     return new static(
80       $container->get('module_handler'),
81       $container->get('entity.manager'),
82       $container->get('renderer')
83     );
84   }
85
86   /**
87    * {@inheritdoc}
88    */
89   public function getFormId() {
90     return 'taxonomy_overview_terms';
91   }
92
93   /**
94    * Form constructor.
95    *
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.
98    *
99    * @param array $form
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.
105    *
106    * @return array
107    *   The form structure.
108    */
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
111     //   in.
112     global $pager_page_array, $pager_total, $pager_total_items;
113
114     $form_state->set(['taxonomy', 'vocabulary'], $taxonomy_vocabulary);
115     $parent_fields = FALSE;
116
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.
121     $page_entries = 0;
122     // Elements at the root level before this page.
123     $before_entries = 0;
124     // Elements at the root level after this page.
125     $after_entries = 0;
126     // Elements at the root level on this page.
127     $root_entries = 0;
128
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.
132     $back_step = NULL;
133     $forward_step = 0;
134
135     // 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     do {
143       // In case this tree is completely empty.
144       if (empty($tree[$tree_index])) {
145         break;
146       }
147       $delta++;
148       // Count entries before the current page.
149       if ($page && ($page * $page_increment) > $before_entries && !isset($back_step)) {
150         $before_entries++;
151         continue;
152       }
153       // Count entries after the current page.
154       elseif ($page_entries > $page_increment && isset($complete_tree)) {
155         $after_entries++;
156         continue;
157       }
158
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)) {
162         $back_step = 0;
163         while ($pterm = $tree[--$tree_index]) {
164           $before_entries--;
165           $back_step++;
166           if ($pterm->depth == 0) {
167             $tree_index--;
168             // Jump back to the start of the root level parent.
169             continue 2;
170           }
171         }
172       }
173       $back_step = isset($back_step) ? $back_step : 0;
174
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.
179         $after_entries++;
180         continue;
181       }
182       if ($page_entries >= $page_increment + $back_step) {
183         $forward_step++;
184       }
185
186       // Finally, if we've gotten down this far, we're rendering a term on this
187       // page.
188       $page_entries++;
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()];
191
192       // Keep track of the first term displayed on this page.
193       if ($page_entries == 1) {
194         $form['#first_tid'] = $term->id();
195       }
196       // Keep a variable to make sure at least 2 root elements are displayed.
197       if ($term->parents[0] == 0) {
198         $root_entries++;
199       }
200       $current_page[$key] = $term;
201     } while (isset($tree[++$tree_index]));
202
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);
208
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
211     // submitted.
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
220         // depth.
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'];
223         }
224         else {
225           unset($current_page[$key]);
226         }
227       }
228     }
229
230     $errors = $form_state->getErrors();
231     $row_position = 0;
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()]);
237     }
238     else {
239       $empty = $this->t('No terms available.');
240     }
241     $form['terms'] = [
242       '#type' => 'table',
243       '#empty' => $empty,
244       '#header' => [
245         'term' => $this->t('Name'),
246         'operations' => $this->t('Operations'),
247         'weight' => $this->t('Weight'),
248       ],
249       '#attributes' => [
250         'id' => 'taxonomy',
251       ],
252     ];
253     $this->renderer->addCacheableDependency($form['terms'], $create_access);
254
255     // Only allow access to changing weights if the user has update access for
256     // all terms.
257     $change_weight_access = AccessResult::allowed();
258     foreach ($current_page as $key => $term) {
259       $form['terms'][$key] = [
260         'term' => [],
261         'operations' => [],
262         'weight' => [],
263       ];
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           '#theme' => 'indentation',
271           '#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           '#type' => 'hidden',
284           '#value' => $term->id(),
285           '#attributes' => [
286             'class' => ['term-id'],
287           ],
288         ];
289         $form['terms'][$key]['term']['parent'] = [
290           '#type' => 'hidden',
291           // Yes, default_value on a hidden. It needs to be changeable by the
292           // javascript.
293           '#default_value' => $term->parents[0],
294           '#attributes' => [
295             'class' => ['term-parent'],
296           ],
297         ];
298         $form['terms'][$key]['term']['depth'] = [
299           '#type' => 'hidden',
300           // Same as above, the depth is modified by javascript, so it's a
301           // default_value.
302           '#default_value' => $term->depth,
303           '#attributes' => [
304             'class' => ['term-depth'],
305           ],
306         ];
307       }
308       $update_access = $term->access('update', NULL, TRUE);
309       $change_weight_access = $change_weight_access->andIf($update_access);
310
311       if ($update_access->isAllowed()) {
312         $form['terms'][$key]['weight'] = [
313           '#type' => 'weight',
314           '#delta' => $delta,
315           '#title' => $this->t('Weight for added term'),
316           '#title_display' => 'invisible',
317           '#default_value' => $term->getWeight(),
318           '#attributes' => ['class' => ['term-weight']],
319         ];
320       }
321
322       if ($operations = $this->termListBuilder->getOperations($term)) {
323         $form['terms'][$key]['operations'] = [
324           '#type' => 'operations',
325           '#links' => $operations,
326         ];
327       }
328
329       $form['terms'][$key]['#attributes']['class'] = [];
330       if ($parent_fields) {
331         $form['terms'][$key]['#attributes']['class'][] = 'draggable';
332       }
333
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';
337       }
338
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';
342         }
343         elseif ($row_position == $back_step || $row_position == $page_entries - $forward_step) {
344           $form['terms'][$key]['#attributes']['class'][] = 'taxonomy-term-divider-bottom';
345         }
346       }
347
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';
352         }
353       }
354       $row_position++;
355     }
356
357     $this->renderer->addCacheableDependency($form['terms'], $change_weight_access);
358     if ($change_weight_access->isAllowed()) {
359       if ($parent_fields) {
360         $form['terms']['#tabledrag'][] = [
361           'action' => 'match',
362           'relationship' => 'parent',
363           'group' => 'term-parent',
364           'subgroup' => 'term-parent',
365           'source' => 'term-id',
366           'hidden' => FALSE,
367         ];
368         $form['terms']['#tabledrag'][] = [
369           'action' => 'depth',
370           'relationship' => 'group',
371           'group' => 'term-depth',
372           'hidden' => FALSE,
373         ];
374         $form['terms']['#attached']['library'][] = 'taxonomy/drupal.taxonomy';
375         $form['terms']['#attached']['drupalSettings']['taxonomy'] = [
376           'backStep' => $back_step,
377           'forwardStep' => $forward_step,
378         ];
379       }
380       $form['terms']['#tabledrag'][] = [
381         'action' => 'order',
382         'relationship' => 'sibling',
383         'group' => 'term-weight',
384       ];
385     }
386
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'] = [
390         '#type' => 'submit',
391         '#value' => $this->t('Save'),
392         '#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     return $form;
403   }
404
405   /**
406    * Form submission handler.
407    *
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.
410    *
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.
417    *
418    * @param array $form
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.
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     if (empty($tree)) {
435       return;
436     }
437
438     // Build a list of all terms that need to be updated on previous pages.
439     $weight = 0;
440     $term = $tree[0];
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;
445       }
446       $weight++;
447       $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
448       $term = $tree[$weight];
449     }
450
451     // Renumber the current page weights and assign any new parents.
452     $level_weights = [];
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;
460         }
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;
467           }
468         }
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;
473         }
474         $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
475         $weight++;
476       }
477     }
478
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;
486       }
487       $hierarchy = $term->parents[0] != 0 ? VocabularyInterface::HIERARCHY_SINGLE : $hierarchy;
488     }
489
490     // Save all updated terms.
491     foreach ($changed_terms as $term) {
492       $term->save();
493     }
494
495     // Update the vocabulary hierarchy to flat or single hierarchy.
496     if ($vocabulary->getHierarchy() != $hierarchy) {
497       $vocabulary->setHierarchy($hierarchy);
498       $vocabulary->save();
499     }
500     $this->messenger()->addStatus($this->t('The configuration options have been saved.'));
501   }
502
503   /**
504    * Redirects to confirmation form for the reset action.
505    */
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 }